---
title: "Differentiation in Protest Politics Participation by Political Insiders and Outsiders"
author: "Endre Borbáth"
date: "Nov. 19, 2022"
output:
  html_document:
    code_folding: hide
    df_print: paged
    theme: paper
    toc: yes
    toc_float:
      collapsed: false
---


# Setting up R

```{r, include = T, echo = T, message = F, include=FALSE}

rm(list = ls()) 

library(foreign)
library(dplyr)
library(corrplot)
library(tidyr)
library(ggplot2)
library(GPArotation)
library(psych)
library(stringr)
library(fastDummies)
library(haven)
library(forcats)
library(DescTools)
library(broom)
library(ggrepel)
library(fmsb)
library(texreg)
library(lubridate)
library(glca)
library(kableExtra)
library(naniar)
library(bife)
library(ggstatsplot)
set.seed(1991)

path <- "path_on_local_HDD/"

fig_path <- paste0(path, "main_text/figures/") # you need to create this folder structure on the local HDD
app_fig_path <- paste0(path, "appendix/figures/")
tables_path <- paste0(path, "appendix/tables/")

setwd(path)


```

# Data management 

```{r, include = T, echo = F, message = F}

orig_dat <- read_dta(paste0(path, "data/Welle I_Final.dta")) %>% 
  mutate_at(vars(issue_racism, issue_climate, issue_corona, issue_corona_eco, issue_other),
            ~as.numeric(.)) %>% 
  mutate(issue=case_when(
    issue_racism==0 & issue_climate==0 & issue_corona==1 & issue_corona_eco ==0 & issue_other==0 ~ "Only corona freedom",
    issue_racism==0 & issue_climate==0 & issue_corona==0 & issue_corona_eco ==1 & issue_other==0 ~ "Only corona economic",  
    issue_racism==0 & issue_climate==0 & issue_corona==1 & issue_corona_eco ==1 & issue_other==0 ~ "Corona both", 
    (issue_corona==1 | issue_corona_eco ==1) & (issue_racism == 1 | issue_climate==1 | issue_other==1) ~ "Corona and other",
    issue_racism==1 & issue_climate==0 & issue_corona==0 & issue_corona_eco ==0 & issue_other==0 ~ "Only racism", 
    issue_racism==0 & issue_climate==1 & issue_corona==0 & issue_corona_eco ==0 & issue_other==0 ~ "Only climate prot.",
    issue_racism==1 & issue_climate==1 & issue_corona==0 & issue_corona_eco ==0 & issue_other==0 ~ "Both racism and climate",
    (issue_corona==0 & issue_corona_eco ==0) & (issue_racism == 1 | issue_climate==1 | issue_other==1) ~ "Other",
    TRUE ~ "No pol. eng.")) %>% 
  mutate(issue=factor(issue, levels = c("Only corona freedom", "Only corona economic",
                                        "Corona both", "Corona and other",
                                        "Only racism", "Only climate prot.", 
                                        "Both racism and climate", 
                                        "Other", "No pol. eng."))) %>% 
    mutate(issue=factor(issue, levels=rev(levels(issue)))) %>% 
  mutate(age2=age*age) %>% 
  mutate(vote_pref=as_factor(vote_pref)) %>% 
  mutate(vote_pref=droplevels(vote_pref)) %>% 
  mutate(vote_pref=fct_explicit_na(vote_pref, "Don't know")) %>% 
  mutate(vote_pref=fct_recode(vote_pref, "NA/DK"="Absence", "NA/DK"="Don't know")) %>% 
  mutate(vote_pref=factor(vote_pref,
                             levels=c("CDU/CSU", "NA/DK", "SPD", "B90/Grüne",
                                      "Linke", "FDP", "AfD", "Other party"))) %>% 
  mutate(represented=case_when(vote_pref %in% c("NA/DK", "AfD", "Other party", "Linke") ~ 0,
                         vote_pref %in% c("CDU/CSU", "SPD", "B90/Grüne", "FDP") ~ 1)) %>% 
   mutate(att_income=as.numeric(att_income)) %>% 
   mutate(att_income=max(att_income, na.rm=TRUE) - att_income+1) %>% 
   mutate(att_migrants=as.numeric(att_migrants)) %>% 
   mutate(lrscale=as.numeric(lrscale)-1) %>%
   mutate_at(vars(lrscale, att_income, att_migrants), ~.-mean(., na.rm=TRUE)) %>% 
   mutate(lrscale_sq=lrscale^2) %>%
   mutate(att_income_sq=att_income^2) %>%
   mutate(att_migrants_sq=att_migrants^2) %>%
   mutate(participation=case_when(pol_demo > 1 | pol_demo_online > 1 | 
                                   pol_post_online > 1 | pol_petition > 1 | 
                                   pol_demo_illegal > 1 ~ 1, TRUE ~ 0)) %>% 
  mutate(regular_participation= case_when(pol_demo > 3 | pol_demo_online > 3 | 
                       pol_post_online > 3 | pol_petition > 3 | 
                       pol_demo_illegal > 3 ~ 1, TRUE ~ 0)) %>% 
  mutate(org_membership = (orga_labour + orga_party + orga_religious + orga_sports + 
           orga_arts + orga_environment + orga_neighbor + orga_humanrights + 
           orga_welfare)) %>% #orga_patriotic, orga_other
  mutate(date = as_datetime(ats)) %>% 
  ungroup(.) %>% 
  mutate(msr_eco=max(msr_eco, na.rm = TRUE)-msr_eco+1,
         worr_climate=max(worr_climate, na.rm = TRUE)-worr_climate+1,
         att_diversity=max(att_diversity, na.rm = TRUE)-att_diversity+1)

```

# Figure 1, main text

```{r, echo = T, message = F}

plot_dat <- orig_dat %>%
  mutate(`No pol. eng.` = case_when(issue=="No pol. eng." ~ 1, 
                                    TRUE ~ 0)) %>% 
  mutate(`Corona freedom`=case_when((pol_demo > 1 | pol_demo_online > 1 | 
                                   pol_post_online > 1 | pol_petition > 1 | 
                                   pol_demo_illegal > 1) & issue_corona==1 ~ 1,
                         TRUE ~ 0)) %>% 
  mutate(`Corona economic`=case_when((pol_demo > 1 | pol_demo_online > 1 | 
                                   pol_post_online > 1 | pol_petition > 1 | 
                                   pol_demo_illegal > 1) & issue_corona_eco==1 ~ 1,
                    TRUE ~ 0)) %>% 
  mutate(`Against racism` = case_when((pol_demo > 1 | pol_demo_online > 1 | 
                                   pol_post_online > 1 | pol_petition > 1 | 
                                   pol_demo_illegal > 1) & issue_racism==1 ~ 1, TRUE ~ 0)) %>% 
  mutate(`Climate prot.` = case_when((pol_demo > 1 | pol_demo_online > 1 | 
                                   pol_post_online > 1 | pol_petition > 1 | 
                                   pol_demo_illegal > 1) & issue_climate==1 ~ 1, TRUE ~ 0)) %>% 
  select(`Corona freedom`, `Corona economic`,
         `Against racism`, `Climate prot.`, `No pol. eng.`, wgt_2) %>% 
  mutate_at(vars(`Corona freedom`, `Corona economic`,
         `Against racism`, `Climate prot.`, `No pol. eng.`), ~ .*wgt_2) %>% 
  mutate_at(vars(`Corona freedom`, `Corona economic`,
         `Against racism`, `Climate prot.`, `No pol. eng.`, wgt_2), ~ sum(., na.rm=TRUE)) %>% 
  distinct(.) %>% 
  mutate_at(vars(`Corona freedom`, `Corona economic`,
         `Against racism`, `Climate prot.`, `No pol. eng.`), ~ .*100/wgt_2) %>% 
  select(-wgt_2) %>% 
  pivot_longer(cols=c("Corona freedom", "Corona economic",
         "Against racism", "Climate prot.", "No pol. eng."), names_to = "issue", values_to = "average") %>% 
  mutate(type="Overall sample")

plot_dat2 <- orig_dat %>%
  filter(issue!="No pol. eng.") %>%
  mutate(`Corona freedom`=case_when((pol_demo > 1 | pol_demo_online > 1 | 
                                   pol_post_online > 1 | pol_petition > 1 | 
                                   pol_demo_illegal > 1) & issue_corona==1 ~ 1,
                         TRUE ~ 0)) %>% 
  mutate(`Corona economic`=case_when((pol_demo > 1 | pol_demo_online > 1 | 
                                   pol_post_online > 1 | pol_petition > 1 | 
                                   pol_demo_illegal > 1) & issue_corona_eco==1 ~ 1,
                    TRUE ~ 0)) %>% 
  mutate(`Against racism` = case_when((pol_demo > 1 | pol_demo_online > 1 | 
                                   pol_post_online > 1 | pol_petition > 1 | 
                                   pol_demo_illegal > 1) & issue_racism==1 ~ 1, TRUE ~ 0)) %>% 
  mutate(`Climate prot.` = case_when((pol_demo > 1 | pol_demo_online > 1 | 
                                   pol_post_online > 1 | pol_petition > 1 | 
                                   pol_demo_illegal > 1) & issue_climate==1 ~ 1, TRUE ~ 0)) %>% 
  select(`Corona freedom`, `Corona economic`,
         `Against racism`, `Climate prot.`, wgt_2) %>% 
  mutate_at(vars(`Corona freedom`, `Corona economic`,
         `Against racism`, `Climate prot.`), ~ .*wgt_2) %>% 
  mutate_at(vars(`Corona freedom`, `Corona economic`,
         `Against racism`, `Climate prot.`, wgt_2), ~ sum(., na.rm=TRUE)) %>% 
  distinct(.) %>% 
  mutate_at(vars(`Corona freedom`, `Corona economic`,
         `Against racism`, `Climate prot.`), ~ .*100/wgt_2) %>% 
  select(-wgt_2) %>% 
  pivot_longer(cols=c("Corona freedom", "Corona economic",
         "Against racism", "Climate prot."), names_to = "issue", values_to = "average") %>% 
  mutate(type="Among noninstutional participants")

plot_dat <- bind_rows(plot_dat, plot_dat2) %>% 
  mutate(type=factor(type, levels=c("Among noninstutional participants", "Overall sample"))) %>% 
  mutate(average=ifelse(issue=="No pol. eng.", 100-average, average)) %>% 
  mutate(issue=case_when(issue == "Corona freedom" ~ "COVID-19: against freedom restrictions",
                         issue == "Corona economic" ~ "COVID-19: for economic assistance",
                         issue == "Against racism" ~ "Against racism",
                         issue == "Climate prot." ~ "For climate protection",
                         issue=="No pol. eng." ~ "Political engagement")) %>% 
  mutate(issue=factor(issue, levels=c("Political engagement",
                                      "For climate protection",
                                      "Against racism",
                                      "COVID-19: against freedom restrictions",
                                      "COVID-19: for economic assistance"))) %>%  
  mutate(issue=fct_rev(issue)) %>% 
  group_by(type) %>% 
  mutate(check=sum(average, na.rm = TRUE)) %>% 
  ungroup(.)

rm(plot_dat2)

ggplot(plot_dat) +
  geom_bar(aes(y=issue, x=average, alpha=type), stat="identity", 
           position = position_dodge(width = 1), fill="#4daf4a", color="black") +
  geom_text(aes(y=issue, x=average-2, 
                label=paste0(round(average, digits=0), "%"), 
                group=type), 
            size = 3, position = position_dodge(width = 1), color="black") +
  scale_alpha_manual(name="", values=c(0.3, 0.8), guide = guide_legend(reverse = TRUE, byrow = TRUE)) +
  ylab("") +
  xlab("Percentage points (pp.)") +
  theme_linedraw() +
  theme(legend.title=element_blank(), 
        legend.position="bottom",
        axis.title.y=element_blank())

ggsave(plot=last_plot(),
       filename = "issues_not_mutually_exclusive.png",
       path=fig_path, scale = 1.3,
       width = 4.5, height = 3, dpi=400)

```

# Appendix A, figure 1

```{r, include = T, echo = F, message = F}

DVs_shcntry <- orig_dat %>% 
  select(pol_demo, pol_demo_online, pol_post_online, pol_petition, pol_demo_illegal, wgt_2) %>% 
  mutate_at(vars(pol_demo, pol_demo_online, pol_post_online, pol_petition, pol_demo_illegal), ~ifelse(as.numeric(.)>1, 1, 0)) %>% 
  mutate_at(vars(pol_demo, pol_demo_online, pol_post_online, pol_petition, pol_demo_illegal), ~as.numeric(.)*wgt_2) %>% 
  mutate_all(~sum(., na.rm = TRUE)) %>% 
  unique(.) %>% 
  mutate_at(vars(pol_demo, pol_demo_online, pol_post_online, pol_petition, pol_demo_illegal), ~.*100/wgt_2) %>% 
  select(-wgt_2) %>% 
  pivot_longer(cols=c(pol_demo, pol_demo_online, pol_post_online, pol_petition, pol_demo_illegal), names_to="indicator", values_to="share") %>% 
  arrange(indicator)

DVs_shcntry_regular <- orig_dat %>% 
  select(pol_demo, pol_demo_online, pol_post_online, pol_petition, pol_demo_illegal, wgt_2) %>% 
  mutate_at(vars(pol_demo, pol_demo_online, pol_post_online, pol_petition, pol_demo_illegal), ~ifelse(as.numeric(.)>3, 1, 0)) %>% 
  mutate_at(vars(pol_demo, pol_demo_online, pol_post_online, pol_petition, pol_demo_illegal), ~as.numeric(.)*wgt_2) %>% 
  mutate_all(~sum(., na.rm = TRUE)) %>% 
  unique(.) %>% 
  mutate_at(vars(pol_demo, pol_demo_online, pol_post_online, pol_petition, pol_demo_illegal), ~.*100/wgt_2) %>% 
  select(-wgt_2) %>% 
  pivot_longer(cols=c(pol_demo, pol_demo_online, pol_post_online, pol_petition, pol_demo_illegal), names_to="indicator", values_to="share_regular") %>% 
  arrange(indicator)

DVS_cntry <- merge(DVs_shcntry, DVs_shcntry_regular)

DVS_cntry <- DVS_cntry %>% 
  mutate(indicator=case_when(
    indicator=="pol_cntct_polit" ~ "Contact a pol.",
    indicator=="pol_demo" ~ "Demo.",
    indicator=="pol_demo_illegal" ~ "Illegal demo.",
    indicator=="pol_demo_online" ~ "Online demo.",
    indicator=="pol_party" ~ "Party activies",
    indicator=="pol_petition" ~ "Petition",
    indicator=="pol_post_online" ~ "Online post"))


rm(DVs_shcntry, DVs_shcntry_regular)

plot_dat <- DVS_cntry %>% 
  select(indicator, share, share_regular) %>% 
  mutate(order=rank(share)) %>% 
  pivot_longer(cols=c(share, share_regular), values_to = "value", names_to = "facets") %>% 
  mutate(facets=case_when(facets=="share" ~ "Overall participation",
                          facets=="share_regular" ~ "Regular participation")) %>% 
  mutate(facets=factor(facets, levels = c("Overall participation", "Regular participation")))

ggplot(plot_dat, aes(y=reorder(indicator, order), x=value)) +
  geom_bar(stat="identity") +
  facet_wrap(~facets, scales="free_x") +
  xlab("Percentage points (pp.)") +
  theme_linedraw() +
  theme(axis.title.y = element_blank()) #axis.text.x = element_text(angle = 90, vjust = 0.5, hjust=1)

ggsave(filename = "forms_share.png",
       path = app_fig_path,
       width = 6.5,
       height = 4,
       pointsize=6)

```

# Appendix A, Figure 2 

```{r, include = T, echo = T, message = F}

plot_dat1 <- orig_dat %>%
  filter(issue!="No pol. eng.") %>%
  mutate(issue_spit = case_when(issue_corona==1 ~ 1, TRUE ~ 0)) %>% 
  select(wgt_2, issue_spit, pol_demo, pol_demo_online, pol_post_online, pol_petition, pol_demo_illegal) %>% 
  mutate_at(vars(pol_demo, pol_demo_online, pol_post_online, pol_petition, pol_demo_illegal), ~ifelse(as.numeric(.)>1, 1, 0))%>%
  mutate_at(vars(pol_demo, pol_demo_online, pol_post_online, pol_petition, pol_demo_illegal), ~.*wgt_2) %>%
  mutate(total=sum(wgt_2, na.rm=TRUE)) %>% 
  group_by(issue_spit) %>% 
  mutate_at(vars(pol_demo, pol_demo_online, pol_post_online, pol_petition, pol_demo_illegal), ~sum(., na.rm=TRUE)) %>% 
  select(pol_demo, pol_demo_online, pol_post_online, pol_petition, pol_demo_illegal) %>% 
  distinct(.) %>% 
  ungroup(.) %>% 
  arrange(issue_spit) %>% 
  mutate_at(vars(pol_demo, pol_demo_online, pol_post_online, pol_petition, pol_demo_illegal), ~ case_when(issue_spit==0 ~ sum(., na.rm=TRUE),
                                                 TRUE ~ .)) %>% 
  mutate_at(vars(pol_demo, pol_demo_online, pol_post_online, pol_petition, pol_demo_illegal), ~.*100/lag(., n = 1L)) %>% 
  filter(issue_spit==1) %>% 
  mutate(issue_spit = "Corona freedom")

plot_dat2 <- orig_dat %>%
  filter(issue!="No pol. eng.") %>%
  mutate(issue_spit = case_when(issue_corona_eco==1 ~ 1, TRUE ~ 0)) %>% 
  select(wgt_2, issue_spit, pol_demo, pol_demo_online, pol_post_online, pol_petition, pol_demo_illegal) %>% 
  mutate_at(vars(pol_demo, pol_demo_online, pol_post_online, pol_petition, pol_demo_illegal), ~ifelse(as.numeric(.)>1, 1, 0))%>%
  mutate_at(vars(pol_demo, pol_demo_online, pol_post_online, pol_petition, pol_demo_illegal), ~.*wgt_2) %>%
  mutate(total=sum(wgt_2, na.rm=TRUE)) %>% 
  group_by(issue_spit) %>% 
  mutate_at(vars(pol_demo, pol_demo_online, pol_post_online, pol_petition, pol_demo_illegal), ~sum(., na.rm=TRUE)) %>% 
  select(pol_demo, pol_demo_online, pol_post_online, pol_petition, pol_demo_illegal) %>% 
  distinct(.) %>% 
  ungroup(.) %>% 
  arrange(issue_spit) %>% 
  mutate_at(vars(pol_demo, pol_demo_online, pol_post_online, pol_petition, pol_demo_illegal), ~case_when(issue_spit==0 ~ sum(., na.rm=TRUE),
                                                 TRUE ~ .)) %>% 
  mutate_at(vars(pol_demo, pol_demo_online, pol_post_online, pol_petition, pol_demo_illegal), ~.*100/lag(., n = 1L)) %>% 
  filter(issue_spit==1) %>% 
  mutate(issue_spit = "Corona economic")

plot_dat3 <- orig_dat %>%
  filter(issue!="No pol. eng.") %>%
  mutate(issue_spit = case_when(issue_climate==1 ~ 1, TRUE ~ 0)) %>% 
  select(wgt_2, issue_spit, pol_demo, pol_demo_online, pol_post_online, pol_petition, pol_demo_illegal) %>% 
  mutate_at(vars(pol_demo, pol_demo_online, pol_post_online, pol_petition, pol_demo_illegal), ~ifelse(as.numeric(.)>1, 1, 0))%>%
  mutate_at(vars(pol_demo, pol_demo_online, pol_post_online, pol_petition, pol_demo_illegal), ~.*wgt_2) %>%
  mutate(total=sum(wgt_2, na.rm=TRUE)) %>% 
  group_by(issue_spit) %>% 
  mutate_at(vars(pol_demo, pol_demo_online, pol_post_online, pol_petition, pol_demo_illegal), ~sum(., na.rm=TRUE)) %>% 
  select(pol_demo, pol_demo_online, pol_post_online, pol_petition, pol_demo_illegal) %>% 
  distinct(.) %>% 
  ungroup(.) %>% 
  arrange(issue_spit) %>% 
  mutate_at(vars(pol_demo, pol_demo_online, pol_post_online, pol_petition, pol_demo_illegal), ~case_when(issue_spit==0 ~ sum(., na.rm=TRUE),
                                                 TRUE ~ .)) %>% 
  mutate_at(vars(pol_demo, pol_demo_online, pol_post_online, pol_petition, pol_demo_illegal), ~.*100/lag(., n = 1L)) %>% 
  filter(issue_spit==1) %>% 
  mutate(issue_spit = "Climate prot.")

plot_dat4 <- orig_dat %>%
  filter(issue!="No pol. eng.") %>%
  mutate(issue_spit = case_when(issue_racism==1 ~ 1, TRUE ~ 0)) %>% 
  select(wgt_2, issue_spit, pol_demo, pol_demo_online, pol_post_online, pol_petition, pol_demo_illegal) %>% 
  mutate_at(vars(pol_demo, pol_demo_online, pol_post_online, pol_petition, pol_demo_illegal), ~ifelse(as.numeric(.)>1, 1, 0))%>%
  mutate_at(vars(pol_demo, pol_demo_online, pol_post_online, pol_petition, pol_demo_illegal), ~.*wgt_2) %>%
  mutate(total=sum(wgt_2, na.rm=TRUE)) %>% 
  group_by(issue_spit) %>% 
  mutate_at(vars(pol_demo, pol_demo_online, pol_post_online, pol_petition, pol_demo_illegal), ~sum(., na.rm=TRUE)) %>% 
  select(pol_demo, pol_demo_online, pol_post_online, pol_petition, pol_demo_illegal) %>% 
  distinct(.) %>% 
  ungroup(.) %>% 
  arrange(issue_spit) %>% 
  mutate_at(vars(pol_demo, pol_demo_online, pol_post_online, pol_petition, pol_demo_illegal), ~case_when(issue_spit==0 ~ sum(., na.rm=TRUE),
                                                 TRUE ~ .)) %>% 
  mutate_at(vars(pol_demo, pol_demo_online, pol_post_online, pol_petition, pol_demo_illegal), ~.*100/lag(., n = 1L)) %>% 
  filter(issue_spit==1) %>% 
  mutate(issue_spit = "Against racism")

plot_dat <- bind_rows(plot_dat1, plot_dat2, 
                      plot_dat3, plot_dat4)

rm(plot_dat1, plot_dat2,
   plot_dat3,plot_dat4)

plot_dat <- plot_dat %>% 
  ungroup(.) %>% 
  pivot_longer(cols=contains("pol_"), values_to="value", names_to="type") %>% 
  mutate(type=case_when(
    type=="pol_cntct_polit" ~ "Contact a pol.",
    type=="pol_demo" ~ "Demo.",
    type=="pol_demo_illegal" ~ "Illegal demo.",
    type=="pol_demo_online" ~ "Online demo.",
    type=="pol_party" ~ "Party activies",
    type=="pol_petition" ~ "Petition",
    type=="pol_post_online" ~ "Online post")) %>%
  mutate(type=factor(type, levels = c("Demo.",
                                      "Illegal demo.",
                                      "Online demo.",
                                      "Online post",
                                      "Petition",
                                      "Contact a pol.",
                                      "Party activies",
                                      "Other polit.")))
plot_dat <- plot_dat %>% 
  rename(issue=issue_spit)

# plot_dat <- merge(plot_dat, plot_dat2, all=TRUE)

plot_dat <- plot_dat %>%
  group_by(issue) %>%
  mutate(average=mean(value, na.rm=TRUE)) %>%
  ungroup(.)

plot_dat <- plot_dat %>%
  mutate(ypos=ifelse(value>=average, value+1, average+1)) %>%
  group_by(issue) %>% 
  mutate(ypos=value+1) %>%
  ungroup(.) %>% 
  mutate(issue=factor(issue, levels=c("Climate prot.",
                                      "Against racism",
                                      "Corona freedom",
                                      "Corona economic"))) %>%
  arrange(type, issue)


plot_dat <- plot_dat %>%
  arrange(issue, type)

number_of_bar <- 5
angle <-  90 - 360 * 
  (as.numeric(as.factor(unique(plot_dat$type)))-0.5) /number_of_bar     # I substract 0.5 because the letter must have the angle of the center of the bars. Not extreme right(1) or extreme left (0)

angle <- rep(angle, length(unique(plot_dat$issue)))

plot_dat$hjust<-ifelse( angle < -90, 1, 0)
 
# flip angle BY to make them readable
plot_dat$angle<-ifelse(angle < -90, angle+180, angle)

plot_dat$label <- as.character(plot_dat$issue)

plot_dat <- plot_dat %>% 
  mutate(label=case_when(label=="Corona freedom" ~ "COVID-19\nfreedom",
                         label=="Corona economic" ~ "COVID-19\necon.",
                         label=="Against racism" ~ "Against\nracism",
                         label=="Climate prot." ~ "Climate\nprot.",
                         TRUE ~ label))

ggplot(plot_dat, aes(x=as.factor(type), y=value)) + 
  # geom_bar(aes(x=as.factor(type), y=average, fill=type), color="black", stat ="identity", alpha=.3, linetype="dashed") +
  geom_bar(stat="identity", aes(fill=type), alpha=0.6, color="black") +
  ylim(-25,55) +
  facet_wrap(~issue, ncol=2) +
  scale_fill_brewer(palette = "Set2",
                    guide = guide_legend(reverse = FALSE, nrow=2, byrow = TRUE)) +
  theme_minimal() +
  theme(legend.title=element_blank(),
    legend.position=c(.5,0),
    axis.text = element_blank(),
    axis.title = element_blank(),
    panel.grid = element_blank(),
    panel.spacing = unit(-4, "lines"),
    plot.margin = unit(c(-1,0,0,0), "cm"),
    strip.background = element_blank(),
    strip.text = element_blank()) +
  coord_polar(start = 0) +
  geom_text(aes(x=type, y=ypos, label=paste0(round(value), "%"), hjust=hjust), color="black",
            fontface="bold", size=2.5, angle= plot_dat$angle, inherit.aes = FALSE ) +
  geom_text(aes(label = label), x = 0.5, y = -25, size=3)

ggsave(filename = "issue_form.png",
       path = app_fig_path,
       width = 5,
       height = 6,
       pointsize=6)

```


# Appendix A, figure 3

```{r, include = T, echo = T, message = F, warning=FALSE, fig.width=6.5, fig.height=10}

overall <- orig_dat %>% 
  ungroup(.) %>% 
  select(contains("orga_"), wgt_2) %>% 
  mutate_at(vars(contains("orga_")), ~.*wgt_2) %>% 
  mutate_all(~sum(., na.rm = TRUE)) %>% 
  distinct(.) %>% 
  mutate_at(vars(contains("orga_")), ~.*100/wgt_2) %>% 
  select(-wgt_2) %>% 
  pivot_longer(cols = everything(), names_to = "organization", values_to = "overall")

overall2 <- orig_dat %>% 
  filter(issue!="No pol. eng.") %>% 
  filter((pol_demo > 1 | pol_demo_online > 1 | 
            pol_post_online > 1 | pol_petition > 1 | 
            pol_demo_illegal > 1)) %>% 
  ungroup(.) %>% 
  select(contains("orga_"), wgt_2) %>% 
  mutate_at(vars(contains("orga_")), ~.*wgt_2) %>% 
  mutate_all(~sum(., na.rm = TRUE)) %>% 
  distinct(.) %>% 
  mutate_at(vars(contains("orga_")), ~.*100/wgt_2) %>% 
  select(-wgt_2) %>% 
  pivot_longer(cols = everything(), names_to = "organization", values_to = "among_participants")

overall <- left_join(overall, overall2)

overall2 <- orig_dat %>% 
  filter(issue_climate==1) %>% 
  filter((pol_demo > 1 | pol_demo_online > 1 | 
            pol_post_online > 1 | pol_petition > 1 | 
            pol_demo_illegal > 1)) %>% 
  ungroup(.) %>% 
  select(contains("orga_"), wgt_2) %>% 
  mutate_at(vars(contains("orga_")), ~.*wgt_2) %>% 
  mutate_all(~sum(., na.rm = TRUE)) %>% 
  distinct(.) %>% 
  mutate_at(vars(contains("orga_")), ~.*100/wgt_2) %>% 
  select(-wgt_2) %>% 
  pivot_longer(cols = everything(), names_to = "organization", values_to = "value") %>% 
  mutate(type="issue_climate")

subseted <- orig_dat %>% 
  filter(issue_racism==1) %>% 
  filter((pol_demo > 1 | pol_demo_online > 1 | 
            pol_post_online > 1 | pol_petition > 1 | 
            pol_demo_illegal > 1)) %>% 
  ungroup(.) %>% 
  select(contains("orga_"), wgt_2) %>% 
  mutate_at(vars(contains("orga_")), ~.*wgt_2) %>% 
  mutate_all(~sum(., na.rm = TRUE)) %>% 
  distinct(.) %>% 
  mutate_at(vars(contains("orga_")), ~.*100/wgt_2) %>% 
  select(-wgt_2) %>% 
  pivot_longer(cols = everything(), names_to = "organization", values_to = "value") %>% 
  mutate(type="issue_racism")

overall2 <- bind_rows(overall2, subseted)

subseted <- orig_dat %>% 
  filter(issue_corona_eco==1) %>% 
  filter((pol_demo > 1 | pol_demo_online > 1 | 
            pol_post_online > 1 | pol_petition > 1 | 
            pol_demo_illegal > 1)) %>% 
  ungroup(.) %>% 
  select(contains("orga_"), wgt_2) %>% 
  mutate_at(vars(contains("orga_")), ~.*wgt_2) %>% 
  mutate_all(~sum(., na.rm = TRUE)) %>% 
  distinct(.) %>% 
  mutate_at(vars(contains("orga_")), ~.*100/wgt_2) %>% 
  select(-wgt_2) %>% 
  pivot_longer(cols = everything(), names_to = "organization", values_to = "value") %>% 
  mutate(type="issue_corona_eco")

overall2 <- bind_rows(overall2, subseted)

subseted <- orig_dat %>% 
  filter(issue_corona==1) %>% 
  filter((pol_demo > 1 | pol_demo_online > 1 | 
            pol_post_online > 1 | pol_petition > 1 | 
            pol_demo_illegal > 1)) %>% 
  ungroup(.) %>% 
  select(contains("orga_"), wgt_2) %>% 
  mutate_at(vars(contains("orga_")), ~.*wgt_2) %>% 
  mutate_all(~sum(., na.rm = TRUE)) %>% 
  distinct(.) %>% 
  mutate_at(vars(contains("orga_")), ~.*100/wgt_2) %>% 
  select(-wgt_2) %>% 
  pivot_longer(cols = everything(), names_to = "organization", values_to = "value") %>% 
  mutate(type="issue_corona")

overall2 <- bind_rows(overall2, subseted)

overall <- merge(overall, overall2)

overall <- overall %>% 
  filter(organization!="none") %>% 
  mutate(organization=str_remove(as.character(organization), "orga_")) %>% 
  filter(organization!="none") %>% 
  filter(organization!="patriotic") %>% 
  filter(organization!="others") %>% 
  mutate(type=case_when(type=="issue_climate" ~ "Climate prot.",
                        type=="issue_racism" ~ "Against racism",
                        type=="issue_corona_eco" ~ "COVID-19 econ.",
                        type=="issue_corona" ~ "COVID-19 freedom")) %>% 
  mutate(type=factor(type, levels = c("Climate prot.", "Against racism", 
                                      "COVID-19 econ.", "COVID-19 freedom"))) %>% 
  mutate(organization=case_when(organization=="arts" ~ "Leisure time org.",
                                organization=="environment" ~ "Environmental org.",
                                organization=="humanrights" ~ "Human rights org.",
                                organization=="labour" ~ "Trade union or prof. org.",
                                organization=="neighbor" ~ "Neighbourhood assoc.",
                                organization=="others" ~ "Other civil soc. org.",
                                organization=="party" ~ "Political party",
                                organization=="patriotic" ~ "Patriotic alliance",
                                organization=="religious" ~ "Religious org.",
                                organization=="sports" ~ "Sports club",
                                organization=="welfare" ~ "Charity org.")) %>% 
  mutate(organization=fct_reorder(organization, among_participants))
  # mutate(type=fct_rev(type))

space_between_bars <- 0.2

overall$type_y_adj = scale(as.numeric(as.factor(overall$type))) * -space_between_bars
overall$y = as.numeric(as.factor(overall$organization)) + overall$type_y_adj

ggplot(overall) + 
  geom_segment(aes(x = among_participants, xend = value, y=y, yend=y, color=type),
               arrow = arrow(length = unit(0.1, "cm"))) +
  scale_y_continuous(breaks = 1:length(unique(overall$organization)),
                     labels = unique(overall$organization), minor_breaks = NULL) +
  scale_color_manual(name="", 
                     values=c("#66C2A5", "#FC8D62", "#8DA0CB", "#E78AC3"),   
                     guide=guide_legend(reverse = FALSE, nrow=1, byrow=TRUE)) +
  xlab("Share of members (percentage points)") +
  theme_linedraw() +
  theme(legend.title=element_blank(), 
        legend.position="bottom",
        legend.key.width = unit(0.5,"cm"),
        axis.title.y = element_blank())

ggsave(filename = "org_members.png",
      path = app_fig_path,
      width = 8,
      height = 7,
      scale=0.8,
      dpi=400)

rm(overall, overall2, subseted)

```

# Regression analysis

## General participation

```{r, include = T, echo = T, message = F, warning=FALSE}

pol_controls <- c("lrscale", "lrscale_sq", "polinterest", "represented",
              "trust_state", "org_membership")

socdem_controls <- c("age", "age2", "edu_lev2", "gndr", "income", "region")

factors <- c("edu_lev2", "gndr", "region", "represented")

reg_dat <- orig_dat %>% 
  select(all_of(c(pol_controls, socdem_controls)), 
                wgt_2, participation, regular_participation) %>% 
  mutate_at(vars(contains("issue_")), ~ replace_na(., 0)) %>% 
  mutate_at(vars(all_of(factors)), ~as.factor(as.character(.))) %>% 
  # mutate_at(vars(contains("pol_")), ~ifelse(.>1, 1, 0)) %>% 
  # mutate_at(vars(contains("pol_")), ~as.factor(.)) %>% 
  # mutate_at(vars(contains("pol_")), ~relevel(., ref = "0")) %>% 
  mutate(edu_lev2=factor(edu_lev2, levels=c("0", "1"))) %>% 
  mutate(region=relevel(region, ref = "1")) %>% 
  mutate(voter=relevel(represented, ref = "0")) %>% 
  ungroup(.) %>% 
  na.omit

M1 <- glm(as.formula(paste0("participation ~ ",
                            paste(pol_controls, collapse = "+"), "+", 
                            paste(socdem_controls, collapse = "+"))),
    data = reg_dat,
    weights = wgt_2,
    family = "binomial")

M2 <- glm(as.formula(paste0("regular_participation ~ ",
                            paste(pol_controls, collapse = "+"), "+", 
                            paste(socdem_controls, collapse = "+"))),
    data = reg_dat,
    weights = wgt_2,
    family = "binomial")

mod1_res <- tidy(M1)
mod1_res <- mod1_res %>% 
  mutate(type="Overall participation")
mod1_ci <- as.data.frame(confint(M1))
mod1_ci$term <- rownames(mod1_ci)
mod1_res <- merge(mod1_ci, mod1_res, by="term", all=TRUE)
mod1_ci <- as.data.frame(confint(M1, level=0.9))
mod1_ci$term <- rownames(mod1_ci)
mod1_res <- merge(mod1_ci, mod1_res, by="term", all=TRUE)
  
mod2_res <- tidy(M2)
mod2_res <- mod2_res %>% 
  mutate(type="Regular participation")
mod2_ci <- as.data.frame(confint(M2))
mod2_ci$term <- rownames(mod2_ci)
mod2_res <- merge(mod2_ci, mod2_res, by="term", all=TRUE)
mod2_ci <- as.data.frame(confint(M2, level=0.9))
mod2_ci$term <- rownames(mod2_ci)
mod2_res <- merge(mod2_ci, mod2_res, by="term", all=TRUE)

models <- bind_rows(mod1_res, mod2_res)

rm(mod1_res, mod2_res, mod1_ci, mod2_ci)

```


```{r, include = T, echo = T, message = F, warning=FALSE}

# insider 0.5281741 

new_dat <- data.frame("lrscale" = mean(reg_dat$lrscale),
                      "lrscale_sq" = quantile(reg_dat$lrscale_sq, probs=c(0.1)),
                         "polinterest" = mean(reg_dat$polinterest),
                         "represented" = as.factor(1),
                         "trust_state" = quantile(reg_dat$trust_state, probs=c(0.9)), 
                         "org_membership" = quantile(reg_dat$org_membership, probs=c(0.9)), 
                         "age" = mean(reg_dat$age),  
                         "age2" = mean(reg_dat$age2), 
                         "edu_lev2" = as.factor(0), 
                         "gndr" = as.factor(1), 
                         "income" = mean(reg_dat$income), 
                         "region" = as.factor(1))

predict(M1, newdata = new_dat, type = "response")

# outsider 0.4981364 

new_dat <- data.frame("lrscale" = mean(reg_dat$lrscale),
                      "lrscale_sq" = quantile(reg_dat$lrscale_sq, probs=c(0.9)),
                         "polinterest" = mean(reg_dat$polinterest),
                         "represented" = as.factor(0),
                         "trust_state" = quantile(reg_dat$trust_state, probs=c(0.1)), 
                         "org_membership" = quantile(reg_dat$org_membership, probs=c(0.1)), 
                         "age" = mean(reg_dat$age),  
                         "age2" = mean(reg_dat$age2), 
                         "edu_lev2" = as.factor(0), 
                         "gndr" = as.factor(1), 
                         "income" = mean(reg_dat$income), 
                         "region" = as.factor(1))

predict(M1, newdata = new_dat, type = "response")

```

### Table 1 Appendix A

```{r, include = T, echo = T, message = F, warning=FALSE}

R2s <- c(PseudoR2(M1, "McFadden"), PseudoR2(M2, "McFadden"))

texreg(l=list(M1, M2), doctype = FALSE, center = TRUE, siunitx=TRUE, use.packages=FALSE, booktabs = TRUE, float.pos = "h!",
       caption = "Individual-level differences in participation in noninstitutional forms",
       single.row=TRUE, no.margin = TRUE,
       custom.model.names = c("Participation", "Regular Participation"),
       # custom.header = list("Corona" = 1, "Corona" = 2,
       #                      "Against" = 3, "Climate" = 4),
       custom.gof.rows = list("McFadden Sq(R)" =  R2s),
       custom.coef.map = list("(Intercept)" = "Intercept",
                              "trust_state" = "Trust in state",
                              "lrscale_sq" = "Sq(L-R scale)",
                              "represented1" = "Dominant party",
                              "org_membership" = "Organisational membership",
                              "polinterest" = "Political interest",
                              "lrscale" = "L-R scale",
                              "age" = "Age",
                              "age2" = "Sq(Age)",
                              "edu_lev21" = "High education",
                              "gndr2" = "Female",
                              "income" = "Income",
                              "region2" = "Mid. town (ref: big city)",
                              "region3" = "Small town",
                              "region4" = "Countryside"),
       groups = list("Insiders - outsiders" = 2:5,
                     "Pol. controls" = 6:7,
                     "Socio-demographics" = 8:15),
       include.deviance = FALSE,
       include.loglik = FALSE,
       file=paste0(tables_path, "general_participation.tex"),
      custom.note	= "%stars. Results are based on the first wave, weighted by the socio-demographic weight.")


# tex <- readLines(paste0(path, "Drafts/tables/general_participation.tex"))
# tex <- tex[-8]
# 
# writeLines(tex, paste0(path, "Drafts/tables/general_participation.tex"))
                                      
```

### Figure 2 Main Text

```{r, include = T, echo = T, message = F, warning=FALSE, fig.width=6.5, fig.height=10}

plot_dat <- models %>% 
  filter(!(term %in% c("(Intercept)"))) %>% 
  mutate(odds = exp(estimate),
         odds.outter.upper = exp(`2.5 %`),
         odds.outter.lower = exp(`97.5 %`),
         odds.inner.upper = exp(`5 %`),
         odds.inner.lower = exp(`95 %`)) %>% 
  mutate(term_orig=term) %>% 
  mutate(term=case_when(term=="age" ~ "Age",
                        term=="age2" ~ "Sq(Age)",
                        term=="edu_lev21" ~ "High educ.",
                        term=="gndr2" ~ "Female",
                        term=="income" ~ "Income",
                        term=="region2" ~ "Mid. town (ref: big city)",
                        term=="region3" ~ "Small town",
                        term=="region4" ~ "Countryside",
                        term=="polinterest" ~ "Pol. interest",
                        term=="lrscale" ~ "L-R scale",
                        term=="trust_state" ~ "Trust in state",
                        term=="org_membership" ~ "Org. Membership",
                        term=="represented1" ~ "Dominant party",
                        term=="lrscale_sq" ~ "Sq(L-R scale)",
                        TRUE ~ term)) 

titles <- plot_dat %>%
  filter(term %in% c("Age", "Sq(Age)", "Income")) %>%  # I just need some unique values
  mutate_at(vars(c(2:9), c(11:16)), ~ NA)

titles$term <- rep(c("Socio-demographics", "Pol. controls", "Insiders - outsiders"), 2)

plot_dat <- bind_rows(plot_dat, titles)

plot_dat <- plot_dat %>% 
  mutate(term=factor(term, levels=c("Insiders - outsiders",
                                    "Trust in state", "Sq(L-R scale)",
                                    "Dominant party", "Org. Membership",
                                    "Pol. controls",
                                    "Pol. interest",
                                    "L-R scale",
                                    "Socio-demographics", 
                                    "Age", "Sq(Age)", "High educ.",
                                    "Female", "Income", "Mid. town (ref: big city)",
                                    "Small town", "Countryside"))) %>% 
  mutate(term=fct_rev(term))

space_between_bars <- 0.8

ggplot(plot_dat, aes(y=term)) +
  geom_vline(xintercept = 1, linetype="dashed", color="gray60") +
  geom_point(aes(x=odds), position=position_dodge(width=space_between_bars), size=2) +
  geom_linerange(aes(xmin=odds.outter.lower, xmax=odds.outter.upper, 
                     group=type), size=0.5, position=position_dodge(width=space_between_bars), key_glyph = "path") +
  geom_linerange(aes(xmin=odds.inner.lower, xmax=odds.inner.upper, 
                     group=type), size=1.1, position=position_dodge(width=space_between_bars), key_glyph = "path") +
  facet_wrap(~type) +
  xlab("Odds Ratio") +
  scale_color_brewer(name="", palette = "Set2", guide=guide_legend(reverse = TRUE, nrow=2, byrow=TRUE)) +
  scale_shape_discrete(name="", guide=guide_legend(reverse = TRUE, nrow=2, byrow=TRUE)) +
  theme_linedraw() +
  theme(legend.title=element_blank(), 
        legend.position="bottom",
        legend.key.width = unit(1,"cm"),
        axis.title.y = element_blank(),
        axis.text.y=element_text(face=c(rep('plain', 8), 'bold', 
                                        rep('plain', 2), 'bold', 
                                        rep('plain', 4), 'bold')),
        # axis.text.y = element_text(face = c(rep(2, 4))),
        axis.ticks.y = element_blank())

ggsave(plot=last_plot(),
       filename="participation.png",
       path = fig_path,
       width=7,
       height=5,
       scale=0.9,
       dpi=400)

```

## With differentiated vote choice

```{r, include = T, echo = T, message = F, warning=FALSE}

pol_controls <- c("lrscale", "lrscale_sq", "polinterest", "vote_pref",
              "trust_state", "org_membership")

socdem_controls <- c("age", "age2", "edu_lev2", "gndr", "income", "region")

factors <- c("edu_lev2", "gndr", "region", "vote_pref")

reg_dat <- orig_dat %>% 
  select(all_of(c(pol_controls, socdem_controls)), 
                wgt_2, participation, regular_participation) %>% 
  mutate_at(vars(contains("issue_")), ~ replace_na(., 0)) %>% 
  mutate_at(vars(all_of(factors)), ~as.factor(as.character(.))) %>% 
  # mutate_at(vars(contains("pol_")), ~ifelse(.>1, 1, 0)) %>% 
  # mutate_at(vars(contains("pol_")), ~as.factor(.)) %>% 
  # mutate_at(vars(contains("pol_")), ~relevel(., ref = "0")) %>% 
  mutate(edu_lev2=factor(edu_lev2, levels=c("0", "1"))) %>% 
  mutate(vote_pref=relevel(vote_pref, ref = "CDU/CSU")) %>% 
  mutate(region=relevel(region, ref = "1")) %>% 
  ungroup(.) %>% 
  na.omit

M1 <- glm(as.formula(paste0("participation ~ ",
                            paste(pol_controls, collapse = "+"), "+", 
                            paste(socdem_controls, collapse = "+"))),
    data = reg_dat,
    weights = wgt_2,
    family = "binomial")

M2 <- glm(as.formula(paste0("regular_participation ~ ",
                            paste(pol_controls, collapse = "+"), "+", 
                            paste(socdem_controls, collapse = "+"))),
    data = reg_dat,
    weights = wgt_2,
    family = "binomial")

mod1_res <- tidy(M1)
mod1_res <- mod1_res %>% 
  mutate(type="Overall participation")
mod1_ci <- as.data.frame(confint(M1))
mod1_ci$term <- rownames(mod1_ci)
mod1_res <- merge(mod1_ci, mod1_res, by="term", all=TRUE)
mod1_ci <- as.data.frame(confint(M1, level=0.9))
mod1_ci$term <- rownames(mod1_ci)
mod1_res <- merge(mod1_ci, mod1_res, by="term", all=TRUE)
  
mod2_res <- tidy(M2)
mod2_res <- mod2_res %>% 
  mutate(type="Regular participation")
mod2_ci <- as.data.frame(confint(M2))
mod2_ci$term <- rownames(mod2_ci)
mod2_res <- merge(mod2_ci, mod2_res, by="term", all=TRUE)
mod2_ci <- as.data.frame(confint(M2, level=0.9))
mod2_ci$term <- rownames(mod2_ci)
mod2_res <- merge(mod2_ci, mod2_res, by="term", all=TRUE)

models <- bind_rows(mod1_res, mod2_res)

rm(mod1_res, mod2_res, mod1_ci, mod2_ci)

```


```{r, include = T, echo = T, message = F, warning=FALSE}

# insider 0.5281741 

new_dat <- data.frame("lrscale" = mean(reg_dat$lrscale),
                      "lrscale_sq" = quantile(reg_dat$lrscale_sq, probs=c(0.1)),
                         "polinterest" = mean(reg_dat$polinterest),
                         "vote_pref" = as.factor("CDU/CSU"),
                         "trust_state" = quantile(reg_dat$trust_state, probs=c(0.9)), 
                         "org_membership" = quantile(reg_dat$org_membership, probs=c(0.9)), 
                         "age" = mean(reg_dat$age),  
                         "age2" = mean(reg_dat$age2), 
                         "edu_lev2" = as.factor(0), 
                         "gndr" = as.factor(1), 
                         "income" = mean(reg_dat$income), 
                         "region" = as.factor(1))

predict(M1, newdata = new_dat, type = "response")

# outsider 0.4981364 

new_dat <- data.frame("lrscale" = mean(reg_dat$lrscale),
                      "lrscale_sq" = quantile(reg_dat$lrscale_sq, probs=c(0.9)),
                         "polinterest" = mean(reg_dat$polinterest),
                         "vote_pref" = as.factor("AfD"),
                         "trust_state" = quantile(reg_dat$trust_state, probs=c(0.1)), 
                         "org_membership" = quantile(reg_dat$org_membership, probs=c(0.1)), 
                         "age" = mean(reg_dat$age),  
                         "age2" = mean(reg_dat$age2), 
                         "edu_lev2" = as.factor(0), 
                         "gndr" = as.factor(1), 
                         "income" = mean(reg_dat$income), 
                         "region" = as.factor(1))

predict(M1, newdata = new_dat, type = "response")

```

### Table 7 Appendix B 

```{r, include = T, echo = T, message = F, warning=FALSE}

R2s <- c(PseudoR2(M1, "McFadden"), PseudoR2(M2, "McFadden"))

texreg(l=list(M1, M2), doctype = FALSE, center = TRUE, siunitx=TRUE, use.packages=FALSE, booktabs = TRUE, float.pos = "h!",
       caption = "Individual-level differences in participation in noninstitutional forms",
       single.row=TRUE, no.margin = TRUE,
       custom.model.names = c("Participation", "Regular Participation"),
       # custom.header = list("Corona" = 1, "Corona" = 2,
       #                      "Against" = 3, "Climate" = 4),
       custom.gof.rows = list("McFadden Sq(R)" =  R2s),
       custom.coef.map = list("(Intercept)" = "Intercept",
                              "trust_state" = "Trust in state",
                              "lrscale_sq" = "Sq(L-R scale)",
                              "org_membership" = "Organisational membership",
                              "vote_prefNA/DK" = "NA/DK",
                              "vote_prefSPD" = "SPD",
                              "vote_prefB90/Grüne" = "B90/Grüne",
                              "vote_prefLinke" = "Linke",
                              "vote_prefFDP" = "FDP",
                              "vote_prefAfD" = "AfD",
                              "vote_prefOther party" = "Other party",
                              "polinterest" = "Political interest",
                              "lrscale" = "L-R scale",
                              "age" = "Age",
                              "age2" = "Sq(Age)",
                              "edu_lev21" = "High education",
                              "gndr2" = "Female",
                              "income" = "Income",
                              "region2" = "Mid. town (ref: big city)",
                              "region3" = "Small town",
                              "region4" = "Countryside"),
       groups = list("Insiders - outsiders" = 2:4,
                     "Parties (ref: CDU/CSU)" = 5:11,
                     "Pol. controls" = 12:13,
                     "Socio-demographics" = 14:21),
       include.deviance = FALSE,
       include.loglik = FALSE,
       file=paste0(tables_path, "general_participation_diff_vote.tex"),
      custom.note	= "%stars. Results are based on the first wave, weighted by the socio-demographic weight.")


# tex <- readLines(paste0(path, "Drafts/tables/general_participation.tex"))
# tex <- tex[-8]
# 
# writeLines(tex, paste0(path, "Drafts/tables/general_participation.tex"))
                                      
```

### Figure 7 Appendix B

```{r, include = T, echo = T, message = F, warning=FALSE, fig.width=6.5, fig.height=10}

plot_dat <- models %>% 
  filter(!(term %in% c("(Intercept)"))) %>% 
  mutate(odds = exp(estimate),
         odds.outter.upper = exp(`2.5 %`),
         odds.outter.lower = exp(`97.5 %`),
         odds.inner.upper = exp(`5 %`),
         odds.inner.lower = exp(`95 %`)) %>% 
  mutate(term_orig=term) %>% 
  mutate(term=case_when(term=="age" ~ "Age",
                        term=="age2" ~ "Sq(Age)",
                        term=="edu_lev21" ~ "High educ.",
                        term=="gndr2" ~ "Female",
                        term=="income" ~ "Income",
                        term=="region2" ~ "Mid. town (ref: big city)",
                        term=="region3" ~ "Small town",
                        term=="region4" ~ "Countryside",
                        term=="polinterest" ~ "Pol. interest",
                        term=="lrscale" ~ "L-R scale",
                        term=="trust_state" ~ "Trust in state",
                        term=="org_membership" ~ "Org. Membership",
                        term=="vote_prefNA/DK" ~ "NA/DK",
                        term=="vote_prefSPD" ~ "SPD",
                        term=="vote_prefB90/Grüne" ~ "B90/Grüne",
                        term=="vote_prefLinke" ~ "Linke",
                        term=="vote_prefFDP" ~ "FDP",
                        term=="vote_prefAfD" ~ "AfD",
                        term=="vote_prefOther party" ~ "Other party",
                        term=="lrscale_sq" ~ "Sq(L-R scale)",
                        TRUE ~ term)) 

titles <- plot_dat %>%
  filter(term %in% c("Age", "Sq(Age)", "Income", "SPD")) %>%  # I just need some unique values
  mutate_at(vars(c(2:9), c(11:16)), ~ NA)

titles$term <- rep(c("Socio-demographics", "Pol. controls", "Insiders - outsiders", "Parties (ref: CDU/CSU)"), 2)

plot_dat <- bind_rows(plot_dat, titles)

plot_dat <- plot_dat %>% 
  mutate(term=factor(term, levels=c("Insiders - outsiders",
                                    "Trust in state", "Sq(L-R scale)",
                                    "Org. Membership", "Parties (ref: CDU/CSU)", "NA/DK",
                                      "SPD",
                                      "B90/Grüne", "Linke",
                                      "FDP", "AfD", "Other party",
                                    "Pol. controls",
                                    "Pol. interest",
                                    "L-R scale",
                                    "Socio-demographics", 
                                    "Age", "Sq(Age)", "High educ.",
                                    "Female", "Income", "Mid. town (ref: big city)",
                                    "Small town", "Countryside"))) %>% 
  mutate(term=fct_rev(term))

space_between_bars <- 0.8

ggplot(plot_dat, aes(y=term)) +
  geom_vline(xintercept = 1, linetype="dashed", color="gray60") +
  geom_point(aes(x=odds), position=position_dodge(width=space_between_bars), size=2) +
  geom_linerange(aes(xmin=odds.outter.lower, xmax=odds.outter.upper, 
                     group=type), size=0.5, position=position_dodge(width=space_between_bars), key_glyph = "path") +
  geom_linerange(aes(xmin=odds.inner.lower, xmax=odds.inner.upper, 
                     group=type), size=1.1, position=position_dodge(width=space_between_bars), key_glyph = "path") +
  facet_wrap(~type) +
  xlab("Odds Ratio") +
  scale_color_brewer(name="", palette = "Set2", guide=guide_legend(reverse = TRUE, nrow=2, byrow=TRUE)) +
  scale_shape_discrete(name="", guide=guide_legend(reverse = TRUE, nrow=2, byrow=TRUE)) +
  theme_linedraw() +
  theme(legend.title=element_blank(), 
        legend.position="bottom",
        legend.key.width = unit(1,"cm"),
        axis.title.y = element_blank(),
        axis.text.y=element_text(face=c(rep('plain', 8), 'bold', 
                                        rep('plain', 2), 'bold', 
                                        rep('plain', 7), 'bold',
                                        rep('plain', 3), 'bold')),
        # axis.text.y = element_text(face = c(rep(2, 4))),
        axis.ticks.y = element_blank())

ggsave(plot=last_plot(),
       filename="participation_diff_vote_choice.png",
       path = app_fig_path,
       width=7,
       height=5,
       scale=0.9,
       dpi=400)

```

## To prepare figure and table 8, Appendix B 

```{r, include = T, echo = T, message = F, warning=FALSE}

pol_controls <- c("att_income", "att_income_sq", 
                  "att_migrants", "att_migrants_sq",
                  "polinterest", "represented",
              "trust_state", "org_membership")

socdem_controls <- c("age", "age2", "edu_lev2", "gndr", "income", "region")

factors <- c("edu_lev2", "gndr", "region", "represented")

reg_dat <- orig_dat %>% 
  select(all_of(c(pol_controls, socdem_controls)), 
                wgt_2, participation, regular_participation) %>% 
  mutate_at(vars(contains("issue_")), ~ replace_na(., 0)) %>% 
  mutate_at(vars(all_of(factors)), ~as.factor(as.character(.))) %>% 
  # mutate_at(vars(contains("pol_")), ~ifelse(.>1, 1, 0)) %>% 
  # mutate_at(vars(contains("pol_")), ~as.factor(.)) %>% 
  # mutate_at(vars(contains("pol_")), ~relevel(., ref = "0")) %>% 
  mutate(edu_lev2=factor(edu_lev2, levels=c("0", "1"))) %>% 
  mutate(represented=relevel(represented, ref = "0")) %>% 
  mutate(region=relevel(region, ref = "1")) %>% 
  ungroup(.) %>% 
  na.omit

M1 <- glm(as.formula(paste0("participation ~ ",
                            paste(pol_controls, collapse = "+"), "+", 
                            paste(socdem_controls, collapse = "+"))),
    data = reg_dat,
    weights = wgt_2,
    family = "binomial")

M2 <- glm(as.formula(paste0("regular_participation ~ ",
                            paste(pol_controls, collapse = "+"), "+", 
                            paste(socdem_controls, collapse = "+"))),
    data = reg_dat,
    weights = wgt_2,
    family = "binomial")

mod1_res <- tidy(M1)
mod1_res <- mod1_res %>% 
  mutate(type="Overall participation")
mod1_ci <- as.data.frame(confint(M1))
mod1_ci$term <- rownames(mod1_ci)
mod1_res <- merge(mod1_ci, mod1_res, by="term", all=TRUE)
mod1_ci <- as.data.frame(confint(M1, level=0.9))
mod1_ci$term <- rownames(mod1_ci)
mod1_res <- merge(mod1_ci, mod1_res, by="term", all=TRUE)
  
mod2_res <- tidy(M2)
mod2_res <- mod2_res %>% 
  mutate(type="Regular participation")
mod2_ci <- as.data.frame(confint(M2))
mod2_ci$term <- rownames(mod2_ci)
mod2_res <- merge(mod2_ci, mod2_res, by="term", all=TRUE)
mod2_ci <- as.data.frame(confint(M2, level=0.9))
mod2_ci$term <- rownames(mod2_ci)
mod2_res <- merge(mod2_ci, mod2_res, by="term", all=TRUE)

models <- bind_rows(mod1_res, mod2_res)

rm(mod1_res, mod2_res, mod1_ci, mod2_ci)

```


### Table 8 Appendix B 

```{r, include = T, echo = T, message = F, warning=FALSE}

R2s <- c(PseudoR2(M1, "McFadden"), PseudoR2(M2, "McFadden"))

texreg(l=list(M1, M2), doctype = FALSE, center = TRUE, siunitx=TRUE, use.packages=FALSE, booktabs = TRUE, float.pos = "h!",
       caption = "Individual-level differences in participation in noninstitutional forms",
       single.row=TRUE, no.margin = TRUE,
       custom.model.names = c("Participation", "Regular Participation"),
       # custom.header = list("Corona" = 1, "Corona" = 2,
       #                      "Against" = 3, "Climate" = 4),
       custom.gof.rows = list("McFadden Sq(R)" =  R2s),
       custom.coef.map = list("(Intercept)" = "Intercept",
                              "trust_state" = "Trust in state",
                              "att_income_sq" = "Sq(gov. intervention)",
                              "att_migrants_sq" = "Sq(migration)",
                              "org_membership" = "Organisational membership",
                              "represented1" = "Dominant party",
                              "polinterest" = "Political interest",
                              "att_income" = "Gov. intervention",
                              "att_migrants" = "Migration",
                              "age" = "Age",
                              "age2" = "Sq(Age)",
                              "edu_lev21" = "High education",
                              "gndr2" = "Female",
                              "income" = "Income",
                              "region2" = "Mid. town (ref: big city)",
                              "region3" = "Small town",
                              "region4" = "Countryside"),
       groups = list("Insiders - outsiders" = 2:6,
                     "Pol. controls" = 7:9,
                     "Socio-demographics" = 10:17),
       include.deviance = FALSE,
       include.loglik = FALSE,
       file=paste0(tables_path, "general_participation_diff_lrscale.tex"),
      custom.note	= "%stars. Results are based on the first wave, weighted by the socio-demographic weight.")


# tex <- readLines(paste0(path, "Drafts/tables/general_participation.tex"))
# tex <- tex[-8]
# 
# writeLines(tex, paste0(path, "Drafts/tables/general_participation.tex"))
                                      
```

### Figure 8 Appendix B

```{r, include = T, echo = T, message = F, warning=FALSE, fig.width=6.5, fig.height=10}

plot_dat <- models %>% 
  filter(!(term %in% c("(Intercept)"))) %>% 
  mutate(odds = exp(estimate),
         odds.outter.upper = exp(`2.5 %`),
         odds.outter.lower = exp(`97.5 %`),
         odds.inner.upper = exp(`5 %`),
         odds.inner.lower = exp(`95 %`)) %>% 
  mutate(term_orig=term) %>% 
  mutate(term=case_when(term=="age" ~ "Age",
                        term=="age2" ~ "Sq(Age)",
                        term=="edu_lev21" ~ "High educ.",
                        term=="gndr2" ~ "Female",
                        term=="income" ~ "Income",
                        term=="region2" ~ "Mid. town (ref: big city)",
                        term=="region3" ~ "Small town",
                        term=="region4" ~ "Countryside",
                        term=="polinterest" ~ "Pol. interest",
                        term=="att_income" ~ "Gov. intervention",
                        term=="att_migrants" ~ "Migration",
                        term=="trust_state" ~ "Trust in state",
                        term=="org_membership" ~ "Org. Membership",
                        term=="represented1" ~ "Dominant party",
                        term=="att_income_sq" ~ "Sq(gov. intervention)",
                        term=="att_migrants_sq" ~ "Sq(migration)",
                        TRUE ~ term)) 

titles <- plot_dat %>%
  filter(term %in% c("Age", "Sq(Age)", "Income")) %>%  # I just need some unique values
  mutate_at(vars(c(2:9), c(11:16)), ~ NA)

titles$term <- rep(c("Socio-demographics", "Pol. controls", "Insiders - outsiders"), 2)

plot_dat <- bind_rows(plot_dat, titles)

plot_dat <- plot_dat %>% 
  mutate(term=factor(term, levels=c("Insiders - outsiders",
                                    "Trust in state", "Sq(gov. intervention)",
                                    "Sq(migration)", "Dominant party", "Org. Membership",
                                    "Pol. controls",
                                    "Pol. interest",
                                    "Gov. intervention", "Migration",
                                    "Socio-demographics", 
                                    "Age", "Sq(Age)", "High educ.",
                                    "Female", "Income", "Mid. town (ref: big city)",
                                    "Small town", "Countryside"))) %>% 
  mutate(term=fct_rev(term))

space_between_bars <- 0.8

ggplot(plot_dat, aes(y=term)) +
  geom_vline(xintercept = 1, linetype="dashed", color="gray60") +
  geom_point(aes(x=odds), position=position_dodge(width=space_between_bars), size=2) +
  geom_linerange(aes(xmin=odds.outter.lower, xmax=odds.outter.upper, 
                     group=type), size=0.5, position=position_dodge(width=space_between_bars), key_glyph = "path") +
  geom_linerange(aes(xmin=odds.inner.lower, xmax=odds.inner.upper, 
                     group=type), size=1.1, position=position_dodge(width=space_between_bars), key_glyph = "path") +
  facet_wrap(~type) +
  xlab("Odds Ratio") +
  scale_color_brewer(name="", palette = "Set2", guide=guide_legend(reverse = TRUE, nrow=2, byrow=TRUE)) +
  scale_shape_discrete(name="", guide=guide_legend(reverse = TRUE, nrow=2, byrow=TRUE)) +
  theme_linedraw() +
  theme(legend.title=element_blank(), 
        legend.position="bottom",
        legend.key.width = unit(1,"cm"),
        axis.title.y = element_blank(),
        axis.text.y=element_text(face=c(rep('plain', 8), 'bold', 
                                        rep('plain', 3), 'bold', 
                                        rep('plain', 5), 'bold')),
        # axis.text.y = element_text(face = c(rep(2, 4))),
        axis.ticks.y = element_blank())

ggsave(plot=last_plot(),
       filename="participation_diff_lrscale.png",
       path = app_fig_path,
       width=7,
       height=5,
       scale=0.9,
       dpi=400)

```

## Table 1 Appendix B 
## Table 2 Appendix B 
## Table 3 Appendix B 
## Table 4 Appendix B 
## Table 5 Appendix B 
## Figure 1 Appendix B 
## Figure 2 Appendix B 
## Figure 3 Appendix B 
## Figure 4 Appendix B 
## Figure 5 Appendix B 


```{r, include = T, echo = T, message = F, warning=FALSE}

pol_controls <- c("lrscale", "lrscale_sq", "polinterest", "represented",
              "trust_state", "org_membership")

socdem_controls <- c("age", "age2", "edu_lev2", "gndr", "income", "region")

factors <- c("edu_lev2", "gndr", "region", "represented")

forms <- c("pol_demo", "pol_demo_online", "pol_post_online",
         "pol_petition", "pol_demo_illegal")

for (i in forms) {

reg_dat <- orig_dat %>% 
  select(all_of(c(pol_controls, socdem_controls, forms)), wgt_2,
         participation, regular_participation) %>% 
  mutate_at(vars(contains("issue_")), ~ replace_na(., 0)) %>% 
  mutate_at(vars(factors), ~as.factor(as.character(.))) %>% 
  mutate(edu_lev2=factor(edu_lev2, levels=c("0", "1"))) %>% 
  mutate(region=relevel(region, ref = "1")) %>% 
  mutate(voter=relevel(represented, ref = "0")) %>% 
  mutate_at(vars(contains("sal_")), ~ relevel(., ref = "0")) %>% 
  ungroup(.) %>% 
  na.omit %>% 
  mutate_at(vars(participation, regular_participation), ~ NA)

reg_dat$participation <- ifelse(reg_dat[i]>1, 1, 0)
reg_dat$regular_participation <- ifelse(reg_dat[i]>3, 1, 0)

M1 <- glm(as.formula(paste0("participation ~ ",
                            paste(pol_controls, collapse = "+"), "+", 
                            paste(socdem_controls, collapse = "+"))),
    data = reg_dat,
    weights = wgt_2,
    family = "binomial")

M2 <- glm(as.formula(paste0("regular_participation ~ ",
                            paste(pol_controls, collapse = "+"), "+", 
                            paste(socdem_controls, collapse = "+"))),
    data = reg_dat,
    weights = wgt_2,
    family = "binomial")

mod1_res <- tidy(M1)
mod1_res <- mod1_res %>% 
  mutate(type="Overall participation")
mod1_ci <- as.data.frame(confint(M1))
mod1_ci$term <- rownames(mod1_ci)
mod1_res <- merge(mod1_ci, mod1_res, by="term", all=TRUE)
mod1_ci <- as.data.frame(confint(M1, level=0.9))
mod1_ci$term <- rownames(mod1_ci)
mod1_res <- merge(mod1_ci, mod1_res, by="term", all=TRUE)
  
mod2_res <- tidy(M2)
mod2_res <- mod2_res %>% 
  mutate(type="Regular participation")
mod2_ci <- as.data.frame(confint(M2))
mod2_ci$term <- rownames(mod2_ci)
mod2_res <- merge(mod2_ci, mod2_res, by="term", all=TRUE)
mod2_ci <- as.data.frame(confint(M2, level=0.9))
mod2_ci$term <- rownames(mod2_ci)
mod2_res <- merge(mod2_ci, mod2_res, by="term", all=TRUE)

models <- bind_rows(mod1_res, mod2_res)

rm(mod1_res, mod2_res, mod1_ci, mod2_ci)

R2s <- c(PseudoR2(M1, "McFadden"), PseudoR2(M2, "McFadden"))

texreg(l=list(M1, M2), doctype = FALSE, center = TRUE, siunitx=TRUE, use.packages=FALSE, booktabs = TRUE, float.pos="h!",
       caption = "Individual-level differences in participation in a specific form",
       single.row=TRUE, no.margin = TRUE,
       custom.model.names = c("Participation", "Regular Participation"),
       custom.gof.rows = list("McFadden Sq(R)" =  R2s),
       custom.coef.map = list("(Intercept)" = "Intercept",
                              "trust_state" = "Trust in state",
                              "lrscale_sq" = "Sq(L-R scale)",
                              "represented1" = "Dominant party",
                              "org_membership" = "Organisational membership",
                              "polinterest" = "Political interest",
                              "lrscale" = "L-R scale",
                              "age" = "Age",
                              "age2" = "Sq(Age)",
                              "edu_lev21" = "High education",
                              "gndr2" = "Female",
                              "income" = "Income",
                              "region2" = "Mid. town (ref: big city)",
                              "region3" = "Small town",
                              "region4" = "Countryside"),
       groups = list("Insiders - outsiders" = 2:5,
                     "Pol. controls" = 6:7,
                     "Socio-demographics" = 8:15),
       include.deviance = FALSE,
       include.loglik = FALSE,
       custom.note	= "%stars. Results are based on the first wave, weighted by the socio-demographic weight.",
       file=paste0(tables_path, i, "gen_part.tex"))


tex <- readLines(paste0(tables_path, i, "gen_part.tex"))
# tex <- tex[-36]

# writeLines(tex, paste0(tables_path, i, "gen_part.tex"))

plot_dat <- models %>% 
  filter(!(term %in% c("(Intercept)"))) %>% 
  mutate(odds = exp(estimate),
         odds.outter.upper = exp(`2.5 %`),
         odds.outter.lower = exp(`97.5 %`),
         odds.inner.upper = exp(`5 %`),
         odds.inner.lower = exp(`95 %`)) %>% 
  mutate(term_orig=term) %>% 
  mutate(term=case_when(term=="age" ~ "Age",
                        term=="age2" ~ "Sq(Age)",
                        term=="edu_lev21" ~ "High educ.",
                        term=="gndr2" ~ "Female",
                        term=="income" ~ "Income",
                        term=="region2" ~ "Mid. town (ref: big city)",
                        term=="region3" ~ "Small town",
                        term=="region4" ~ "Countryside",
                        term=="polinterest" ~ "Pol. interest",
                        term=="lrscale" ~ "L-R scale",
                        term=="trust_state" ~ "Trust in state",
                        term=="org_membership" ~ "Org. Membership",
                        term=="represented1" ~ "Dominant party",
                        term=="lrscale_sq" ~ "Sq(L-R scale)",
                        TRUE ~ term)) 

titles <- plot_dat %>%
  filter(term %in% c("Age", "Sq(Age)", "Income")) %>%  # I just need some unique values
  mutate_at(vars(c(2:9), c(11:16)), ~ NA)

titles$term <- rep(c("Socio-demographics", "Pol. controls", "Insiders - outsiders"), 2)

plot_dat <- bind_rows(plot_dat, titles)

plot_dat <- plot_dat %>% 
  mutate(term=factor(term, levels=c("Insiders - outsiders",
                                    "Trust in state", "Sq(L-R scale)",
                                    "Dominant party", "Org. Membership",
                                    "Pol. controls",
                                    "Pol. interest",
                                    "L-R scale",
                                    "Socio-demographics", 
                                    "Age", "Sq(Age)", "High educ.",
                                    "Female", "Income", "Mid. town (ref: big city)",
                                    "Small town", "Countryside"))) %>% 
  mutate(term=fct_rev(term))

space_between_bars <- 0.8

ggplot(plot_dat, aes(y=term)) +
  geom_vline(xintercept = 1, linetype="dashed", color="gray60") +
  geom_point(aes(x=odds), position=position_dodge(width=space_between_bars), size=2) +
  geom_linerange(aes(xmin=odds.outter.lower, xmax=odds.outter.upper, 
                     group=type), size=0.5, position=position_dodge(width=space_between_bars), key_glyph = "path") +
  geom_linerange(aes(xmin=odds.inner.lower, xmax=odds.inner.upper, 
                     group=type), size=1.1, position=position_dodge(width=space_between_bars), key_glyph = "path") +
  facet_wrap(~type) +
  xlab("Odds Ratio") +
  scale_color_brewer(name="", palette = "Set2", guide=guide_legend(reverse = TRUE, nrow=2, byrow=TRUE)) +
  scale_shape_discrete(name="", guide=guide_legend(reverse = TRUE, nrow=2, byrow=TRUE)) +
  theme_linedraw() +
  theme(legend.title=element_blank(), 
        legend.position="bottom",
        legend.key.width = unit(1,"cm"),
        axis.title.y = element_blank(),
        axis.text.y=element_text(face=c(rep('plain', 8), 'bold', 
                                        rep('plain', 2), 'bold', 
                                        rep('plain', 4), 'bold')),
        # axis.text.y = element_text(face = c(rep(2, 4))),
        axis.ticks.y = element_blank())

ggsave(plot=last_plot(),
       filename=paste0(i, "part.png"),
       path = app_fig_path,
       width=7,
       height=5,
       scale=0.9,
       dpi=400)

}

```


# LCA 

## Figure 5 Appendix A 

```{r, include = F, echo = F, message = F, results=F}

pol_controls <- c("msr_health", "msr_eco", 
                  "polinterest", "vote_pref", "att_diversity", 
                  "worr_climate", "trust_state", "org_membership", 
                  "lrscale", "lrscale_sq", "represented",
                  "att_income", "att_migrants", "att_income_sq", "att_migrants_sq")

factors <- c("edu_lev2", "gndr", "region", "represented")

socdem_controls <- c("age", "age2", "edu_lev2", "gndr", "income", "region")

forms <- c("pol_demo", "pol_demo_online", "pol_post_online",
         "pol_petition", "pol_demo_illegal")


reg_dat <- orig_dat %>% 
  mutate_at(vars(issue_racism, issue_climate, issue_corona, issue_corona_eco, issue_other),
            ~as.numeric(.)) %>% 
  mutate_at(vars(issue_racism, issue_climate, issue_corona, issue_corona_eco, issue_other), ~ 
              ifelse(((pol_cntct_polit > 1 | pol_party > 1) &
              (pol_demo==1 & pol_demo_online==1 & pol_post_online==1 &
                 pol_petition==1 & pol_demo_illegal==1)), as.numeric(NA), .)) %>% 
  mutate_at(vars(contains("issue_")), ~ case_when(issue=="No pol. eng." ~ as.numeric(NA),
                                                  TRUE ~ .)) %>% 
  select(pol_controls, socdem_controls, wgt_2, issue_corona, 
         issue_corona_eco, issue_climate, issue_racism, issue_other, forms) %>% 
  # mutate_at(vars(contains("issue_")), ~ replace_na(., 0)) %>%
  mutate_at(vars(factors), ~as.factor(as.numeric(.))) %>% 
  mutate(edu_lev2=factor(edu_lev2, levels=c("0", "1"))) %>% 
  mutate(region=relevel(region, ref = "1")) %>% 
  ungroup(.) %>% 
  mutate_at(vars(contains("issue_")), ~.+1) %>% 
  na.omit


library(poLCA)

entropy<-function (p) sum(-p*log(p), na.rm = TRUE)

nr_classes <- 6

results <- expand.grid(Models = c("1 Class", paste0(seq(2, nr_classes, 1), " Classes")),
                       BIC = as.numeric(NA),
                       AIC = as.numeric(NA),
                       Chisq = as.numeric(NA),
                       likelihood_ratio = as.numeric(NA),
                       # ABIC = as.numeric(NA),
                       CAIC = as.numeric(NA),
                       R2_entropy = as.numeric(NA))

for (i in seq(1, nr_classes, 1)) {
  lcm <- poLCA::poLCA(cbind(issue_racism, issue_climate, issue_corona, issue_corona_eco)~1,
            nclass = i,
            na.rm = FALSE,
            maxiter=10000,
            data=reg_dat)
  results$BIC[i] <- lcm$bic
  results$AIC[i] <- lcm$aic
  results$Chisq[i] <- lcm$Chisq
  results$likelihood_ratio[i] <- lcm$Gsq
  # results$ABIC[i] = (-2*lcm$llik) + ((log((lcm$N + 2)/24)) * lcm$npar)
  # results$CAIC[i] = (-2*lcm$llik) + lcm$npar * (1 + log(lcm$N))
  results$CAIC[i] = -2 * lcm$llik + (log(lcm$N) + 1L) * lcm$npar
  error_prior <- entropy(lcm$P)
  error_post<-mean(apply(lcm$posterior,1, entropy),na.rm = TRUE)
  results$R2_entropy[i] <- (error_prior - error_post) / error_prior

}


detach("package:poLCA")
detach("package:MASS")

results_long <- results %>% 
  pivot_longer(cols = c(BIC:R2_entropy), names_to = "statistics", values_to = "value") %>% 
  mutate(selected=ifelse(Models=="2 Classes", 1, 0)) %>% 
  mutate(statistics = case_when(statistics=="likelihood_ratio" ~ "Likelihood-ratio",
                                statistics=="R2_entropy" ~ "Entropy R2",
                                TRUE ~ statistics)) %>% 
  mutate(statistics = factor(statistics, levels = c("BIC", "AIC", "CAIC", "Chisq", "Likelihood-ratio", "Entropy R2")))

ggplot(results_long, aes(x=Models, y=value)) +
  geom_point(aes(shape=factor(selected), size=factor(selected))) +
  geom_line(aes(group=1)) +
  facet_grid(statistics ~., scales = "free") +
  # scale_color_manual(values = c("black", "red")) +
  scale_shape_manual(values = c(16, 13)) +
  scale_size_manual(values = c(1.5, 4)) +
  theme_linedraw() +
  theme(axis.title.x = element_blank(),
        legend.position = "none")

ggsave(plot=last_plot(),
       path=app_fig_path,
       filename = "poLCA_fit.png",
       width=5,
       height=6)

```


## 2 classes model

```{r, include = T, echo = F, message = F}

reg_dat <- reg_dat %>% 
    mutate_at(vars(contains("issue_")), ~.-1)

M2 <- glca(item(issue_racism, issue_climate, issue_corona, issue_corona_eco) ~ 1,
            nclass = 2,
            maxiter = 10000,
            seed = 1991,
            data=reg_dat)

summary(M2)

reg_dat <- cbind(reg_dat, as.data.frame(M2$posterior$ALL))

reg_dat <- reg_dat %>% 
  mutate(pred.class=case_when(`Class 1` < 0.5 & `Class 2` > 0.5 ~ "Class 2",
                              `Class 1` > 0.5 & `Class 2` < 0.5 ~ "Class 1",
                              TRUE ~ as.character(NA)))

prop.table(table(reg_dat$pred.class, useNA = "always")) # share in the pop

# Class 1   Class 2      <NA> 
# 0.5879245 0.4120755 0.0000000 

```

## Figure 3 Main Text

```{r, include = T, echo = F, message = F}

plot_dat <- reshape2::melt(M2$param$rho$ALL, level=2) %>% #lcm$param$rho$ALL
  mutate(L2 = case_when(L2=="issue_climate" ~ "Climate prot.",
                        L2=="issue_racism" ~ "Against racism",
                        L2=="issue_corona_eco" ~ "COVID-19 econ.",
                        L2=="issue_corona" ~ "COVID-19 freedom",
                        L2=="issue_other" ~ "Other")) %>% 
  mutate(L2=factor(L2, levels = c("Climate prot.", "Against racism", 
                                  "COVID-19 econ.", "COVID-19 freedom", "Other"))) %>% 
  filter(Var2=="Y = 2")

ggplot(plot_dat, aes(x = L2, y = value, group=Var1)) + 
  geom_point(aes(shape=Var1)) +
  geom_line(aes(linetype=Var1)) +
  theme_linedraw() + 
  ylim(0, 1) +
  labs(x = "Survey Items", y="LCA conditional probabilities") + 
  theme(axis.title.x = element_blank(),
        legend.title=element_blank(),
        legend.position="bottom",
        legend.key.width = unit(2,"cm")) + 
  guides(fill = guide_legend(reverse=TRUE))
        

ggsave(plot=last_plot(),
       path=fig_path,
       filename = "plot_class_2.png",
       width=6,
       height=3.5)

```

```{r, include = T, echo = F, message = F}

starters <- list(M2$param)

M2a <- glca(item(issue_racism, issue_climate, issue_corona, issue_corona_eco) ~
              pol_demo + pol_demo_online + pol_post_online +
              pol_petition + pol_demo_illegal + 
              lrscale + lrscale_sq + msr_health + msr_eco + polinterest +
              represented + att_diversity + worr_climate + trust_state +
              org_membership + age + age2 + edu_lev2 +
              gndr + income + region,
            seed=1991,
            nclass = 2,
            maxit=10000,
            n.init = 1,
            data=reg_dat)

M2b <- glca(item(issue_racism, issue_climate, issue_corona, issue_corona_eco) ~
              pol_demo + pol_demo_online + pol_post_online +
              pol_petition + pol_demo_illegal + 
              lrscale + lrscale_sq + msr_health + msr_eco + polinterest +
              vote_pref + att_diversity + worr_climate + trust_state +
              org_membership + age + age2 + edu_lev2 +
              gndr + income + region,
            seed=1991,
            nclass = 2,
            maxit=10000,
            n.init = 1,
            data=reg_dat)

# coef(M2)

```

## Table 2 Appendix A

```{r, include = T, echo = F, message = F}

first <- as.data.frame(coef(M2a)) %>% 
  mutate(model="Model 1") %>% 
  add_rownames(var = "term")

second <- as.data.frame(coef(M2b)) %>% 
  mutate(model="Model 2") %>% 
  add_rownames(var = "term")

mod_res <- rbind(first, second) 

mod_res <- mod_res %>% 
  rename(odds=ALL.Class1.2.Odds.Ratio,
         Coefficient = ALL.Class1.2.Coefficient,
         SE = ALL.Class1.2..Std..Error,
         `T-statistic` = ALL.Class1.2..t.value,
         `P-value` = ALL.Class1.2..Pr...t..) %>% 
  select(-odds) %>% 
  mutate(stars = case_when(`P-value`<0.05 & `P-value` >=0.01 ~ "*",
                           `P-value`<0.01 & `P-value` >=0.001 ~ "**",
                           `P-value`<0.001 ~ "***",
                           TRUE ~ "")) %>% 
  mutate_at(vars(Coefficient, SE), ~as.character(round(., digits=2))) %>% 
  mutate_at(vars(Coefficient, SE), ~ifelse(.=="0", "0.00", .)) %>% 
  mutate_at(vars(Coefficient, SE), ~ifelse(.=="-0", "-0.00", .)) %>% 
  mutate_at(vars(Coefficient, SE), ~case_when(nchar(.) < 4 ~ paste0(., "0"),
                                              TRUE ~ .)) %>% 
    mutate_at(vars(Coefficient, SE), ~case_when(nchar(.) < 4 ~ paste0(., "0"),
                                              TRUE ~ .)) %>% 
    mutate_at(vars(Coefficient, SE), ~case_when(nchar(.) < 4 ~ paste0(., "0"),
                                              TRUE ~ .)) %>% 
    mutate_at(vars(Coefficient, SE), ~ifelse(.=="0.00", "0.01", .)) %>% 
    mutate_at(vars(Coefficient, SE), ~ifelse(.=="-0.00", "-0.01", .)) %>% 
  # mutate(Coefficient = paste0(Coefficient, stars, "    ", "(", SE, ")")) %>%
  mutate(Coefficient = paste0(Coefficient, stars)) %>%
  mutate(SE = paste0("(", SE, ")")) %>%
  # mutate_at(vars(SE, `T-statistic`, `P-value`), ~ as.character(.)) %>% 
  select(-stars, -`T-statistic`, - `P-value`) %>% 
  mutate(term=str_remove(as.character(term), "vote_pref")) %>%
  mutate(term=case_when(term=="(Intercept)" ~ "Intercept",
                        term=="(issue_climate)1" ~ "Climate protection",
                        term=="(issue_corona_eco)1" ~ "Corona economy",
                        term=="(issue_corona)1" ~ "Corona freedom",
                        term=="(issue_other)1" ~ "Other issue",
                        term=="(issue_racism)1" ~ "Against racism",
                        term=="worr_climate" ~ "Climate concerns",
                        term=="att_diversity" ~ "Diversity",
                        term=="msr_health" ~ "Health measures",
                        term=="msr_eco" ~ "Economic measures",
                        term=="org_membership" ~ "Org. Membership",
                        term=="polinterest" ~ "Political interest",
                        term=="trust_state" ~ "Trust in state",
                        term=="edu_lev21" ~ "High educ.",
                        term=="gndr2" ~ "Female",
                        term=="region2" ~ "Mid. town (ref: big city)",
                        term=="region3" ~ "Small town",
                        term=="region4" ~ "Countryside",
                        term=="pol_demo" ~ "Public demo.", 
                        term=="pol_demo_online" ~ "Online demo.", 
                        term=="pol_post_online" ~ "Posting online", 
                        term=="pol_petition" ~ "Petitions", 
                        term=="pol_demo_illegal" ~ "Illegal demo.",
                        term=="age" ~ "Age",
                        term=="age2" ~ "Sq(Age)",
                        term=="income" ~ "Income",
                        term=="Extreme left" ~ "Extreme left (ref: centre)",
                        term=="represented1" ~ "Dominant party",
                        term=="lrscale" ~ "L-R scale",
                        term=="lrscale_sq" ~ "Sq(L-R scale)",
                        TRUE ~ term)) %>% 
  mutate(term=factor(term, levels = c("Intercept",
                                      "Trust in state",
                                      "Sq(L-R scale)",
                                      "Org. Membership",
                                      "Dominant party",
                                      "NA/DK",
                                      "SPD",
                                      "B90/Grüne", "Linke",
                                      "FDP", "AfD", "Other party",
                                      "Climate concerns",
                                      "Diversity",
                                      "Health measures",
                                      "Economic measures", 
                                      "Public demo.", "Online demo.", "Posting online", 
                                      "Petitions", "Illegal demo.", "Other polit. form",
                                      "Socio-demog. and controls", 
                                      "Political interest", "L-R scale",
                                      "Age", "Sq(Age)", "High educ.", "Female", 
                                      "Income", "Mid. town (ref: big city)", 
                                      "Small town", "Countryside"))) %>%
  arrange(term)

options(knitr.table.format = "latex")
options(knitr.kable.NA = '')

mod_res <- pivot_wider(mod_res, id_cols=term, names_from = model, values_from=c(Coefficient, SE)) %>% 
  rename(coef1=`Coefficient_Model 1`,
         coef2=`Coefficient_Model 2`,
         se1=`SE_Model 1`,
         se2=`SE_Model 2`) %>% 
  select(term, coef1, se1, coef2, se2)

colnames(mod_res) <- c("", "Coef", "SE", "Coef", "SE")

mod_res <- mod_res %>%
  kbl(caption = "Logistic Coefficient Estimates for Latent Class Analysis",
      booktabs = T, format = "latex") %>%
  add_header_above(c(" ", "Model 1" = 2, "Model 2" = 2)) %>%
  pack_rows("Insiders - outsiders", 2, 5) %>%
  pack_rows("Parties (ref: CDU/CSU)", 6, 12) %>%
  pack_rows("Issue preferences", 13, 16) %>%
  pack_rows("Forms of participation", 17, 21) %>%
  pack_rows("Socio-demographics and controls", 22, 31) %>%
  row_spec(0, bold = TRUE) %>%
  add_footnote("***p<0.001; **p<0.01; *p<0.05", notation="none")

writeLines(mod_res, paste0(tables_path, "/LCA_reg_table.tex"))

tex <- readLines(paste0(tables_path, "/LCA_reg_table.tex"))
tex[53] <- "\\multicolumn{5}{l}{\\textsuperscript{} $^{***}p<0.001$; $^{**}p<0.01$; $^{*}p<0.05$}\\\\"
writeLines(tex, paste0(tables_path, "/LCA_reg_table.tex"))

```

## Figure 4 Main Text

```{r, include = T, echo = F, message = F}


mod_res <- as.data.frame(coef(M2b)) %>% 
  rename(odds=ALL.Class1.2.Odds.Ratio,
         coefs = ALL.Class1.2.Coefficient,
         se = ALL.Class1.2..Std..Error,
         t = ALL.Class1.2..t.value,
         p = ALL.Class1.2..Pr...t..) %>% 
  add_rownames(var = "term") %>% 
  mutate(upper=coefs + (1.96*se),
         lower=coefs - (1.96*se)) %>% 
  mutate(odds.upper = exp(upper),
         odds.lower = exp(lower)) %>% 
  filter(!(grepl("pol_", term) | grepl("(Intercept)", term))) %>%
  mutate(term=str_remove(as.character(term), "vote_pref")) %>%
  mutate(term=case_when(term=="worr_climate" ~ "Climate concerns",
                        term=="att_diversity" ~ "Diversity",
                        term=="msr_health" ~ "Health measures",
                        term=="msr_eco" ~ "Economic measures",
                        term=="org_membership" ~ "Org. Membership",
                        term=="polinterest" ~ "Political interest",
                        term=="trust_state" ~ "Trust in state",
                        term=="lrscale" ~ "L-R scale",
                        term=="lrscale_sq" ~ "Sq(L-R scale)",
                        term=="edu_lev21" ~ "High educ.",
                        term=="gndr2" ~ "Female",
                        term=="region2" ~ "Mid. town (ref: big city)",
                        term=="region3" ~ "Small town",
                        term=="region4" ~ "Countryside",
                        term=="age" ~ "Age",
                        term=="age2" ~ "Sq(Age)",
                        term=="income" ~ "Income",
                        term=="Extreme left" ~ "Extreme left (ref: centre)",
                        TRUE ~ term)) %>% 
  mutate(term=factor(term, levels = c("Climate concerns",
                                      "Diversity",
                                      "Health measures",
                                      "Economic measures", 
                                      "Political interest",
                                      "L-R scale",
                                      "Trust in state",
                                      "Sq(L-R scale)",
                                      "Org. Membership",
                                      "CDU/CSU", "NA/DK", "SPD",
                                      "B90/Grüne", "Linke",
                                      "FDP", "AfD", "Other party",
                                      "Age", "Sq(Age)", "High educ.", 
                                      "Female", "Income", "Mid. town (ref: big city)", 
                                      "Small town", "Countryside"))) %>%
  mutate(term=fct_rev(term)) %>%
  mutate(facets=case_when(term %in% c("CDU/CSU", "NA/DK", "SPD",
                                      "B90/Grüne", "Linke", 
                                      "FDP", "AfD", "Other party") ~ "Parties (ref: CDU/CSU)",
                          term %in% c("Climate concerns",
                                      "Diversity",
                                      "Health measures", 
                                      "Economic measures") ~ "Issue preferences",
                          term %in% c("Political interest", "L-R scale", 
                                      "Age", "Sq(Age)", "High educ.", 
                                      "Female", "Mid. town (ref: big city)", 
                                      "Small town", "Countryside", 
                                      "Income") ~ "Socio-demographics & controls",
                          term %in% c("Trust in state",
                                      "Sq(L-R scale)",
                                      "Org. Membership") ~ "Insiders-outsiders")) %>% 
  mutate(facets=factor(facets, levels=c("Insiders-outsiders", 
                                        "Parties (ref: CDU/CSU)",
                                        "Issue preferences", 
                                        "Socio-demographics & controls"))) %>% 
  mutate(new_labels = as.character(term))



ggplot(mod_res, aes(y=term, group=term)) +
  geom_vline(xintercept = 1, linetype="dashed", color="gray60") +
  geom_point(aes(x=odds), size=2) +
  geom_linerange(aes(xmin=odds.lower, xmax=odds.upper), size=1.1, key_glyph = "path") +
  facet_wrap(~facets, scales="free_y", nrow = 2) +
  xlab("Odds Ratio") +
  scale_y_discrete(labels = function(y) stringr::str_wrap(y, width = 15)) +
  theme_linedraw() +
  theme(legend.title=element_blank(),
        legend.position="bottom",
        legend.key.width = unit(1,"cm"),
        axis.title.y = element_blank(),
        axis.text.y = element_text(hjust=0.5))

ggsave(plot=last_plot(),
       path=fig_path,
       filename = "LCA_covariates_with_facets.png",
       width=12.39824,
       height=10,
       scale=1.4,
       dpi=400,
       units="cm")

```

### differentiated left-right scale

```{r, include = T, echo = F, message = F}

starters <- list(M2$param)

M2a <- glca(item(issue_racism, issue_climate, issue_corona, issue_corona_eco) ~
              pol_demo + pol_demo_online + pol_post_online +
              pol_petition + pol_demo_illegal + 
              att_income + att_income_sq + att_migrants + att_migrants_sq + 
              msr_health + msr_eco + polinterest +
              represented + att_diversity + worr_climate + trust_state +
              org_membership + age + age2 + edu_lev2 +
              gndr + income + region,
            seed=1991,
            nclass = 2,
            maxit=10000,
            n.init = 1,
            data=reg_dat)

M2b <- glca(item(issue_racism, issue_climate, issue_corona, issue_corona_eco) ~
              pol_demo + pol_demo_online + pol_post_online +
              pol_petition + pol_demo_illegal + 
              att_income + att_income_sq + att_migrants + att_migrants_sq + 
              msr_health + msr_eco + polinterest +
              vote_pref + att_diversity + worr_climate + trust_state +
              org_membership + age + age2 + edu_lev2 +
              gndr + income + region,
            seed=1991,
            nclass = 2,
            maxit=10000,
            n.init = 1,
            data=reg_dat)

# coef(M2)

```

## Table 9 Appendix B

```{r, include = T, echo = F, message = F}

first <- as.data.frame(coef(M2a)) %>% 
  mutate(model="Model 1") %>% 
  add_rownames(var = "term")

second <- as.data.frame(coef(M2b)) %>% 
  mutate(model="Model 2") %>% 
  add_rownames(var = "term")

mod_res <- rbind(first, second) 

mod_res <- mod_res %>% 
  rename(odds=ALL.Class1.2.Odds.Ratio,
         Coefficient = ALL.Class1.2.Coefficient,
         SE = ALL.Class1.2..Std..Error,
         `T-statistic` = ALL.Class1.2..t.value,
         `P-value` = ALL.Class1.2..Pr...t..) %>% 
  select(-odds) %>% 
  mutate(stars = case_when(`P-value`<0.05 & `P-value` >=0.01 ~ "*",
                           `P-value`<0.01 & `P-value` >=0.001 ~ "**",
                           `P-value`<0.001 ~ "***",
                           TRUE ~ "")) %>% 
  mutate_at(vars(Coefficient, SE), ~as.character(round(., digits=2))) %>% 
  mutate_at(vars(Coefficient, SE), ~ifelse(.=="0", "0.00", .)) %>% 
  mutate_at(vars(Coefficient, SE), ~ifelse(.=="-0", "-0.00", .)) %>% 
  mutate_at(vars(Coefficient, SE), ~case_when(nchar(.) < 4 ~ paste0(., "0"),
                                              TRUE ~ .)) %>% 
    mutate_at(vars(Coefficient, SE), ~case_when(nchar(.) < 4 ~ paste0(., "0"),
                                              TRUE ~ .)) %>% 
    mutate_at(vars(Coefficient, SE), ~case_when(nchar(.) < 4 ~ paste0(., "0"),
                                              TRUE ~ .)) %>% 
    mutate_at(vars(Coefficient, SE), ~ifelse(.=="0.00", "0.01", .)) %>% 
    mutate_at(vars(Coefficient, SE), ~ifelse(.=="-0.00", "-0.01", .)) %>% 
  # mutate(Coefficient = paste0(Coefficient, stars, "    ", "(", SE, ")")) %>%
  mutate(Coefficient = paste0(Coefficient, stars)) %>%
  mutate(SE = paste0("(", SE, ")")) %>%
  # mutate_at(vars(SE, `T-statistic`, `P-value`), ~ as.character(.)) %>% 
  select(-stars, -`T-statistic`, - `P-value`) %>% 
  mutate(term=str_remove(as.character(term), "vote_pref")) %>%
  mutate(term=case_when(term=="(Intercept)" ~ "Intercept",
                        term=="(issue_climate)1" ~ "Climate protection",
                        term=="(issue_corona_eco)1" ~ "Corona economy",
                        term=="(issue_corona)1" ~ "Corona freedom",
                        term=="(issue_other)1" ~ "Other issue",
                        term=="(issue_racism)1" ~ "Against racism",
                        term=="worr_climate" ~ "Climate concerns",
                        term=="att_diversity" ~ "Diversity",
                        term=="msr_health" ~ "Health measures",
                        term=="msr_eco" ~ "Economic measures",
                        term=="org_membership" ~ "Org. Membership",
                        term=="polinterest" ~ "Political interest",
                        term=="trust_state" ~ "Trust in state",
                        term=="edu_lev21" ~ "High educ.",
                        term=="gndr2" ~ "Female",
                        term=="region2" ~ "Mid. town (ref: big city)",
                        term=="region3" ~ "Small town",
                        term=="region4" ~ "Countryside",
                        term=="pol_demo" ~ "Public demo.", 
                        term=="pol_demo_online" ~ "Online demo.", 
                        term=="pol_post_online" ~ "Posting online", 
                        term=="pol_petition" ~ "Petitions", 
                        term=="pol_demo_illegal" ~ "Illegal demo.",
                        term=="age" ~ "Age",
                        term=="age2" ~ "Sq(Age)",
                        term=="income" ~ "Income",
                        term=="Extreme left" ~ "Extreme left (ref: centre)",
                        term=="represented1" ~ "Dominant party",
                        term=="att_income" ~ "Gov. intervention",
                        term=="att_migrants" ~ "Migration",
                        term=="att_income_sq" ~ "Sq(gov. intervention)",
                        term=="att_migrants_sq" ~ "Sq(migration)",
                        TRUE ~ term)) %>% 
  mutate(term=factor(term, levels = c("Intercept",
                                      "Trust in state",
                                      "Sq(gov. intervention)",
                                      "Sq(migration)",
                                      "Org. Membership",
                                      "Dominant party",
                                      "NA/DK",
                                      "SPD",
                                      "B90/Grüne", "Linke",
                                      "FDP", "AfD", "Other party",
                                      "Climate concerns",
                                      "Diversity",
                                      "Health measures",
                                      "Economic measures", 
                                      "Public demo.", "Online demo.", "Posting online", 
                                      "Petitions", "Illegal demo.", 
                                      "Other polit. form",
                                      "Socio-demog. and controls", 
                                      "Political interest", "Gov. intervention",
                                      "Migration",
                                      "Age", "Sq(Age)", "High educ.", "Female", 
                                      "Income", "Mid. town (ref: big city)", 
                                      "Small town", "Countryside"))) %>%
  arrange(term)

options(knitr.table.format = "latex")
options(knitr.kable.NA = '')

mod_res <- pivot_wider(mod_res, id_cols=term, names_from = model, values_from=c(Coefficient, SE)) %>% 
  rename(coef1=`Coefficient_Model 1`,
         coef2=`Coefficient_Model 2`,
         se1=`SE_Model 1`,
         se2=`SE_Model 2`) %>% 
  select(term, coef1, se1, coef2, se2)

colnames(mod_res) <- c("", "Coef", "SE", "Coef", "SE")

mod_res <- mod_res %>%
  kbl(caption = "Logistic Coefficient Estimates for Latent Class Analysis",
      booktabs = T, format = "latex") %>%
  add_header_above(c(" ", "Model 1" = 2, "Model 2" = 2)) %>%
  pack_rows("Insiders - outsiders", 2, 6) %>%
  pack_rows("Parties (ref: CDU/CSU)", 7, 13) %>%
  pack_rows("Issue preferences", 14, 17) %>%
  pack_rows("Forms of participation", 18, 22) %>%
  pack_rows("Socio-demographics and controls", 23, 33) %>%
  row_spec(0, bold = TRUE) %>%
  add_footnote("***p<0.001; **p<0.01; *p<0.05", notation="none")

writeLines(mod_res, paste0(tables_path, "/LCA_reg_table_diff_lrscale.tex"))

tex <- readLines(paste0(tables_path, "/LCA_reg_table_diff_lrscale.tex"))
tex[55] <- "\\multicolumn{5}{l}{\\textsuperscript{} $^{***}p<0.001$; $^{**}p<0.01$; $^{*}p<0.05$}\\\\"
writeLines(tex, paste0(tables_path, "/LCA_reg_table_diff_lrscale.tex"))

```

## Figure 9 Appendix B

```{r, include = T, echo = F, message = F}


mod_res <- as.data.frame(coef(M2b)) %>% 
  rename(odds=ALL.Class1.2.Odds.Ratio,
         coefs = ALL.Class1.2.Coefficient,
         se = ALL.Class1.2..Std..Error,
         t = ALL.Class1.2..t.value,
         p = ALL.Class1.2..Pr...t..) %>% 
  add_rownames(var = "term") %>% 
  mutate(upper=coefs + (1.96*se),
         lower=coefs - (1.96*se)) %>% 
  mutate(odds.upper = exp(upper),
         odds.lower = exp(lower)) %>% 
  filter(!(grepl("pol_", term) | grepl("(Intercept)", term))) %>%
  mutate(term=str_remove(as.character(term), "vote_pref")) %>%
  mutate(term=case_when(term=="worr_climate" ~ "Climate concerns",
                        term=="att_diversity" ~ "Diversity",
                        term=="msr_health" ~ "Health measures",
                        term=="msr_eco" ~ "Economic measures",
                        term=="org_membership" ~ "Org. Membership",
                        term=="polinterest" ~ "Political interest",
                        term=="trust_state" ~ "Trust in state",
                        term=="edu_lev21" ~ "High educ.",
                        term=="gndr2" ~ "Female",
                        term=="region2" ~ "Mid. town (ref: big city)",
                        term=="region3" ~ "Small town",
                        term=="region4" ~ "Countryside",
                        term=="age" ~ "Age",
                        term=="age2" ~ "Sq(Age)",
                        term=="income" ~ "Income",
                        term=="Extreme left" ~ "Extreme left (ref: centre)",
                        term=="att_income" ~ "Gov. intervention",
                        term=="att_migrants" ~ "Migration",
                        term=="att_income_sq" ~ "Sq(gov. intervention)",
                        term=="att_migrants_sq" ~ "Sq(migration)",
                        TRUE ~ term)) %>% 
  mutate(term=factor(term, levels = c("Climate concerns",
                                      "Diversity",
                                      "Health measures",
                                      "Economic measures", 
                                      "Political interest",
                                      "Gov. intervention", "Migration",
                                      "Trust in state",
                                      "Sq(gov. intervention)", "Sq(migration)",
                                      "Org. Membership",
                                      "CDU/CSU", "NA/DK", "SPD",
                                      "B90/Grüne", "Linke",
                                      "FDP", "AfD", "Other party",
                                      "Age", "Sq(Age)", "High educ.", 
                                      "Female", "Income", "Mid. town (ref: big city)", 
                                      "Small town", "Countryside"))) %>%
  mutate(term=fct_rev(term)) %>%
  mutate(facets=case_when(term %in% c("CDU/CSU", "NA/DK", "SPD",
                                      "B90/Grüne", "Linke", 
                                      "FDP", "AfD", "Other party") ~ "Parties (ref: CDU/CSU)",
                          term %in% c("Climate concerns",
                                      "Diversity",
                                      "Health measures", 
                                      "Economic measures") ~ "Issue preferences",
                          term %in% c("Political interest", 
                                      "Gov. intervention", "Migration",
                                      "Age", "Sq(Age)", "High educ.", 
                                      "Female", "Mid. town (ref: big city)", 
                                      "Small town", "Countryside", 
                                      "Income") ~ "Socio-demographics & controls",
                          term %in% c("Trust in state",
                                      "Sq(gov. intervention)", "Sq(migration)",
                                      "Org. Membership") ~ "Insiders-outsiders")) %>% 
  mutate(facets=factor(facets, levels=c("Insiders-outsiders", 
                                        "Parties (ref: CDU/CSU)",
                                        "Issue preferences", 
                                        "Socio-demographics & controls"))) %>% 
  mutate(new_labels = as.character(term))



ggplot(mod_res, aes(y=term, group=term)) +
  geom_vline(xintercept = 1, linetype="dashed", color="gray60") +
  geom_point(aes(x=odds), size=2) +
  geom_linerange(aes(xmin=odds.lower, xmax=odds.upper), size=1.1, key_glyph = "path") +
  facet_wrap(~facets, scales="free_y", nrow = 2) +
  xlab("Odds Ratio") +
  scale_y_discrete(labels = function(y) stringr::str_wrap(y, width = 15)) +
  theme_linedraw() +
  theme(legend.title=element_blank(),
        legend.position="bottom",
        legend.key.width = unit(1,"cm"),
        axis.title.y = element_blank(),
        axis.text.y = element_text(hjust=0.5))

ggsave(plot=last_plot(),
       path=app_fig_path,
       filename = "LCA_covariates_with_facets_diff_LR.png",
       width=12.39824,
       height=12,
       scale=1.4,
       dpi=400,
       units="cm")

```

## individual engagement profiles with only participants

```{r, include = T, echo = T, message = F, warning=FALSE}

pol_controls <- setdiff(pol_controls, c("represented", "att_migrants", 
                                        "att_migrants_sq", "att_income", "att_income_sq"))

M1 <- glm(as.formula(paste0("issue_corona ~ as.factor(issue_corona_eco) + 
                            as.factor(issue_climate) + as.factor(issue_racism) +",
                            paste(forms, collapse = "+"), "+", 
                            paste(pol_controls, collapse = "+"), "+", 
                            paste(socdem_controls, collapse = "+"))),
    data = reg_dat,
    weights = wgt_2,
    family = "binomial")
M2 <- glm(as.formula(paste0("issue_corona_eco ~ as.factor(issue_corona) + 
                            as.factor(issue_climate) + as.factor(issue_racism) +",
                            paste(forms, collapse = "+"), "+", 
                            paste(pol_controls, collapse = "+"), "+", 
                            paste(socdem_controls, collapse = "+"))),
    data = reg_dat,
    weights = wgt_2,
    family = "binomial")

M3 <- glm(as.formula(paste0("issue_climate ~ as.factor(issue_corona) + 
                             as.factor(issue_corona_eco) + as.factor(issue_racism) +",
                            paste(forms, collapse = "+"), "+", 
                            paste(pol_controls, collapse = "+"), "+", 
                            paste(socdem_controls, collapse = "+"))),
    data = reg_dat,
    weights = wgt_2,
    family = "binomial")

M4 <- glm(as.formula(paste0("issue_racism ~ as.factor(issue_corona) + as.factor(issue_corona_eco) +
                            as.factor(issue_climate) +",
                            paste(forms, collapse = "+"), "+", 
                            paste(pol_controls, collapse = "+"), "+", 
                            paste(socdem_controls, collapse = "+"))),
    data = reg_dat,
    weights = wgt_2,
    family = "binomial")

mod1_res <- tidy(M1)
mod1_res <- mod1_res %>% 
  mutate(type="COVID-19 freedom")
mod1_ci <- as.data.frame(confint(M1))
mod1_ci$term <- rownames(mod1_ci)
mod1_res <- merge(mod1_ci, mod1_res, by="term", all=TRUE)
mod1_ci <- as.data.frame(confint(M1, level=0.9))
mod1_ci$term <- rownames(mod1_ci)
mod1_res <- merge(mod1_ci, mod1_res, by="term", all=TRUE)
  
mod2_res <- tidy(M2)
mod2_res <- mod2_res %>% 
  mutate(type="COVID-19 econ.")
mod2_ci <- as.data.frame(confint(M2))
mod2_ci$term <- rownames(mod2_ci)
mod2_res <- merge(mod2_ci, mod2_res, by="term", all=TRUE)
mod2_ci <- as.data.frame(confint(M2, level=0.9))
mod2_ci$term <- rownames(mod2_ci)
mod2_res <- merge(mod2_ci, mod2_res, by="term", all=TRUE)

mod3_res <- tidy(M3)
mod3_res <- mod3_res %>% 
  mutate(type="Climate prot.")
mod3_ci <- as.data.frame(confint(M3))
mod3_ci$term <- rownames(mod3_ci)
mod3_res <- merge(mod3_ci, mod3_res, by="term", all=TRUE)
mod3_ci <- as.data.frame(confint(M3, level=0.9))
mod3_ci$term <- rownames(mod3_ci)
mod3_res <- merge(mod3_ci, mod3_res, by="term", all=TRUE)

mod4_res <- tidy(M4)
mod4_res <- mod4_res %>% 
  mutate(type="Against racism")
mod4_ci <- as.data.frame(confint(M4))
mod4_ci$term <- rownames(mod4_ci)
mod4_res <- merge(mod4_ci, mod4_res, by="term", all=TRUE)
mod4_ci <- as.data.frame(confint(M4, level=0.9))
mod4_ci$term <- rownames(mod4_ci)
mod4_res <- merge(mod4_ci, mod4_res, by="term", all=TRUE)

models <- bind_rows(mod1_res, mod2_res, mod3_res, mod4_res)

rm(mod1_res, mod2_res, mod3_res, mod4_res,
                    mod1_ci, mod2_ci, mod3_ci, mod4_ci)

```

### Table 6 Appendix B 

```{r, include = T, echo = T, message = F, warning=FALSE}

R2s <- c(PseudoR2(M3, "McFadden"), PseudoR2(M4, "McFadden"),
         PseudoR2(M2, "McFadden"), PseudoR2(M1, "McFadden"))

texreg(l=list(M3, M4, M2, M1), doctype = FALSE, center = TRUE, siunitx=TRUE, use.packages=FALSE, booktabs = TRUE,
       caption = "Logit models: issue specific participation", scalebox=0.9, float.pos="h!",
       single.row=TRUE, no.margin = TRUE,
       # custom.model.names = c("Climate", "Against rac.",
       #                        "Cov. Econ.", "Cov. Free."),
       custom.header = list("Climate" = 1:1, "Against rac." = 2:2,
                            "Cov. Econ." = 3:3, "Cov. Freed." = 4:4),
       custom.gof.rows = list("McFadden Sq(R)" =  R2s),
       custom.coef.map = list("(Intercept)"="Intercept",
                              "trust_state" = "Trust in state",
                              "lrscale_sq" = "Sq(L-R scale)",
                              "org_membership" = "Org. Membership",
                              "vote_prefNA/DK" = "NA/DK",
                              "vote_prefSPD" = "SPD",
                              "vote_prefB90/Grüne" = "B90/Grüne",
                              "vote_prefLinke" = "Linke",
                              "vote_prefFDP" = "FDP",
                              "vote_prefAfD" = "AfD",
                              "vote_prefOther party" = "Other party",
                              "worr_climate" = "Climate concerns",
                              "att_diversity" = "Diversity",
                              "msr_health" = "Health measures",
                              "msr_eco" = "Econ. measures",
                              "pol_demo" = "Public demo.", 
                              "pol_demo_online" = "Online demo.", 
                              "pol_post_online" = "Posting online", 
                              "pol_petition"= "Petitions", 
                              "pol_demo_illegal" = "Illegal demo.",
                              "polinterest" = "Pol. interest",
                              "lrscale" = "L-R scale",
                              "age" = "Age",
                              "age2" = "Sq(Age)",
                              "edu_lev21" = "High educ.",
                              "gndr2" = "Female",
                              "income" = "Income",
                              "region2" = "Mid. town (ref: big c.)",
                              "region3" = "Small town",
                              "region4" = "Countryside",
                              "as.factor(issue_climate)1" = "Climate prot.",
                              "as.factor(issue_racism)1" = "Against racism",
                              "as.factor(issue_corona_eco)1" = "Corona econ.",
                              "as.factor(issue_corona)1" = "Corona freedom",
                              "as.factor(issue_other)1" = "Other issue"),
       groups = list("Insiders - outsiders"=2:4,
                     "Parties (ref: CDU/CSU)" = 5:11,
                     "Issue preferences" = 12:15,
                     "Forms of participation" = 16:20,
                     "Socio-demog. \\& controls" = 21:30,
                     "Part. on other iss."=31:34),
       include.deviance = FALSE,
       include.loglik = FALSE,
       custom.note	= "%stars. Results are based on the first wave, weighted by the socio-demographic weight.",
       file=paste0(tables_path, "/issue_specific_reg_part.tex"))

tex <- readLines(paste0(tables_path, "/issue_specific_reg_part.tex"))
tex <- tex[-9]
tex <- tex[-9]

writeLines(tex, paste0(tables_path, "/issue_specific_reg_part.tex"))
                                      
```

### Figure 6 Appendix B

```{r, include = T, echo = T, message = F, warning=FALSE, fig.width=6.5, fig.height=10}

plot_dat <- models %>% 
  filter(term!="(Intercept)") %>% 
  # filter(!(term %in% c("age", "age2", "edu_lev21", 
  #                      "gndr2", "income", "pol_demo", 
  #                      "pol_demo_illegal", "pol_demo_online", 
  #                      "pol_other", "pol_petition", "pol_post_online", 
  #                      "region2", "region3", "region4"))) %>% 
  mutate(odds = exp(estimate),
         odds.outter.upper = exp(`2.5 %`),
         odds.outter.lower = exp(`97.5 %`),
         odds.inner.upper = exp(`5 %`),
         odds.inner.lower = exp(`95 %`),
         probability = odds/(1+odds),
         prob.outter.upper = odds.outter.upper/(1+odds.outter.upper),
         prob.outter.lower = odds.outter.lower/(1+odds.outter.lower),
         prob.inner.upper = odds.inner.upper/(1+odds.inner.upper),
         prob.inner.lower = odds.inner.lower/(1+odds.inner.lower)) %>% 
  mutate(term=str_remove(as.character(term), "as.factor")) %>%
  mutate(term=str_remove(as.character(term), "vote_pref")) %>%
  mutate(term=case_when(term=="(issue_climate)1" ~ "Climate protection",
                        term=="(issue_corona_eco)1" ~ "Corona economy",
                        term=="(issue_corona)1" ~ "Corona freedom",
                        term=="(issue_other)1" ~ "Other issue",
                        term=="(issue_racism)1" ~ "Against racism",
                        term=="worr_climate" ~ "Climate concerns",
                        term=="att_diversity" ~ "Diversity",
                        term=="msr_health" ~ "Health measures",
                        term=="msr_eco" ~ "Economic measures",
                        term=="org_membership" ~ "Org. Membership",
                        term=="polinterest" ~ "Political interest",
                        term=="lrscale" ~ "L-R scale",
                        term=="trust_state" ~ "Trust in state",
                        term=="lrscale_sq" ~ "Sq(L-R scale)",
                        term=="edu_lev21" ~ "High educ.",
                        term=="gndr2" ~ "Female",
                        term=="region2" ~ "Mid. town",
                        term=="region3" ~ "Small town",
                        term=="region4" ~ "Countryside",
                        term=="age" ~ "Age",
                        term=="age2" ~ "Sq(Age)",
                        term=="income" ~ "Income",
                        term=="pol_demo" ~ "Public demo.", 
                        term=="pol_demo_online" ~ "Online demo.", 
                        term=="pol_post_online" ~ "Posting online", 
                        term=="pol_petition" ~ "Petitions", 
                        term=="pol_demo_illegal" ~ "Illegal demo.",
                        TRUE ~ term)) %>% 
  mutate(term=factor(term, levels = c("Climate concerns",
                                      "Diversity",
                                      "Health measures",
                                      "Economic measures", 
                                      "Political interest",
                                      "L-R scale",
                                      "Trust in state",
                                      "Sq(L-R scale)",
                                      "Org. Membership",
                                      "CDU/CSU", "NA/DK", "SPD",
                                      "B90/Grüne", "Linke",
                                      "FDP", "AfD", "Other party",
                                      "Public demo.", "Illegal demo.", 
                                      "Online demo.", "Other form", 
                                      "Petitions", "Posting online",
                                      "Age", "Sq(Age)", "High educ.", 
                                      "Female", "Income", "Mid. town", 
                                      "Small town", "Countryside",
                                      "Climate protection", "Against racism", 
                                      "Corona economy", "Corona freedom",
                                      "Other issue"))) %>%
  mutate(term=fct_rev(term)) %>%
  mutate(facets=case_when(term %in% c("Climate protection", 
                                      "Corona economy", 
                                      "Other issue", 
                                      "Against racism",
                                      "Corona freedom") ~ "Part. on other issues",
                          term %in% c("Public demo.", "Illegal demo.", 
                                      "Online demo.", "Other form", 
                                      "Petitions", 
                                      "Posting online") ~ "Forms of participation",
                          term %in% c("CDU/CSU", "NA/DK", "SPD",
                                      "B90/Grüne", "Linke", 
                                      "FDP", "AfD", "Other party") ~ "Parties (ref: CDU/CSU)",
                          term %in% c("Climate concerns",
                                      "Diversity",
                                      "Health measures", 
                                      "Economic measures") ~ "Issue preferences",
                          term %in% c("Political interest", "L-R scale",
                                      "Age", "Sq(Age)", "High educ.", 
                                      "Female", "Mid. town", 
                                      "Small town", "Countryside", 
                                      "Income") ~ "Socio-demog. & controls",
                          term %in% c("Trust in state",
                                      "Sq(L-R scale)",
                                      "Org. Membership") ~ "Insiders-outsiders")) %>% 
  mutate(facets=factor(facets, levels=c("Insiders-outsiders", 
                                        "Parties (ref: CDU/CSU)",
                                        "Issue preferences", 
                                        "Socio-demog. & controls",
                                        "Forms of participation",
                                        "Part. on other issues"))) %>% 
  mutate(new_labels = as.character(term))

unique(plot_dat$term)

# titles <- plot_dat %>%
#   filter(term %in% c("SPD", "AfD")) %>%  # I just need some unique values
#   mutate_at(vars(c(2:9), c(11:20)), ~ NA)
# "Org. embeddedness", 
                                    
# titles$term <- c(rep("Position", 4), rep("Salience", 4))
# 
# plot_dat <- bind_rows(plot_dat, titles)

space_between_bars <- 0.7

ggplot(plot_dat, aes(y=term, color=type)) +
  geom_vline(xintercept = 1, linetype="dashed", color="gray60") +
  geom_point(aes(x=odds, shape=type), position=position_dodge(width=space_between_bars), size=2) +
  geom_linerange(aes(xmin=odds.outter.lower, xmax=odds.outter.upper, 
                     group=type), size=0.5, position=position_dodge(width=space_between_bars), key_glyph = "path") +
  geom_linerange(aes(xmin=odds.inner.lower, xmax=odds.inner.upper, 
                     group=type), size=1.1, position=position_dodge(width=space_between_bars), key_glyph = "path") +
  xlab("Odds Ratio") +
  facet_wrap(~facets, scales="free_y", nrow = 2) +
  scale_color_manual(name="", values=c("#E78AC3", "#8DA0CB", "#FC8D62", "#66C2A5"), guide=guide_legend(reverse = TRUE, nrow=1, byrow=TRUE)) +
  scale_shape_discrete(name="", guide=guide_legend(reverse = TRUE, nrow=1, byrow=TRUE)) +
  scale_y_discrete(labels = function(y) stringr::str_wrap(y, width = 10)) +
  theme_linedraw() +
  theme(legend.title=element_blank(), 
        legend.position="bottom",
        legend.key.width = unit(1,"cm"),
        axis.title.y = element_blank(),
        axis.text.y = element_text(hjust=0.5))

ggsave(plot=last_plot(),
       filename="issue_specific_reg_part.png",
       path = app_fig_path,
       width=14.32,
       height=21.5,
       scale=1.4,
       dpi=400,
       units="cm")

```


### Figure 5 Main Text

```{r, include = T, echo = T, message = F, warning=FALSE, fig.width=6.5, fig.height=10}

# No pol. eng. 67.034410 70.438685

plot_dat <- read_dta(paste0(path, "/data/DE_Panel_complete_wide.dta")) %>%
  mutate(issue_racism_w1=case_when((pol_demo_w1 > 1 | pol_demo_online_w1 > 1 | 
                                   pol_post_online_w1 > 1 | pol_petition_w1 > 1 | 
                                   pol_demo_illegal_w1 > 1) & issue_racism_w1==1 ~ 1,
                         TRUE ~ as.numeric(NA)),
         issue_climate_w1=case_when((pol_demo_w1 > 1 | pol_demo_online_w1 > 1 | 
                                   pol_post_online_w1 > 1 | pol_petition_w1 > 1 | 
                                   pol_demo_illegal_w1 > 1) & issue_climate_w1==1 ~ 1,
                         TRUE ~ as.numeric(NA)),
         issue_corona_w1=case_when((pol_demo_w1 > 1 | pol_demo_online_w1 > 1 | 
                                   pol_post_online_w1 > 1 | pol_petition_w1 > 1 | 
                                   pol_demo_illegal_w1 > 1) & issue_corona_w1==1 ~ 1,
                         TRUE ~ as.numeric(NA)),
         issue_corona_eco_w1=case_when((pol_demo_w1 > 1 | pol_demo_online_w1 > 1 | 
                                   pol_post_online_w1 > 1 | pol_petition_w1 > 1 | 
                                   pol_demo_illegal_w1 > 1) & issue_corona_eco_w1==1 ~ 1,
                         TRUE ~ as.numeric(NA)),
         issue_racism_w2=case_when((pol_demo_w2 > 1 | pol_demo_online_w2 > 1 | 
                                   pol_post_online_w2 > 1 | pol_petition_w2 > 1 | 
                                   pol_demo_illegal_w2 > 1) & issue_racism_w2==1 ~ 1,
                         TRUE ~ as.numeric(NA)),
         issue_climate_w2=case_when((pol_demo_w2 > 1 | pol_demo_online_w2 > 1 | 
                                   pol_post_online_w2 > 1 | pol_petition_w2 > 1 | 
                                   pol_demo_illegal_w2 > 1) & issue_climate_w2==1 ~ 1,
                         TRUE ~ as.numeric(NA)),
         issue_corona_w2=case_when((pol_demo_w2 > 1 | pol_demo_online_w2 > 1 | 
                                   pol_post_online_w2 > 1 | pol_petition_w2 > 1 | 
                                   pol_demo_illegal_w2 > 1) & issue_corona_w2==1 ~ 1,
                         TRUE ~ as.numeric(NA)),
         issue_corona_eco_w2=case_when((pol_demo_w2 > 1 | pol_demo_online_w2 > 1 | 
                                   pol_post_online_w2 > 1 | pol_petition_w2 > 1 | 
                                   pol_demo_illegal_w2 > 1) & issue_corona_eco_w2==1 ~ 1,
                         TRUE ~ as.numeric(NA))) %>% 
     select(c("issue_racism_w1", "issue_climate_w1", "issue_corona_w1", "issue_corona_eco_w1", 
           "issue_racism_w2", "issue_climate_w2", "issue_corona_w2", "issue_corona_eco_w2", 
           "wgt_2_w1", "wgt_2_w1_adj")) %>% 
  mutate(no_eng_w1=case_when(is.na(issue_racism_w1) & is.na(issue_climate_w1) &
                          is.na(issue_corona_w1) & is.na(issue_corona_eco_w1) ~ 1,
                          TRUE ~ 0),
         no_eng_w2=case_when(is.na(issue_racism_w2) & is.na(issue_climate_w2) &
                          is.na(issue_corona_w2) & is.na(issue_corona_eco_w2) ~ 1,
                          TRUE ~ 0)) %>% 
  mutate_at(vars(contains("issue")), ~ as.numeric(as.character(as.factor(.)))) %>% 
  mutate_at(vars(contains("issue")), ~ if_else(is.na(.), 0, .)) %>% 
  mutate_at(vars(issue_racism_w1, issue_climate_w1,
                 issue_corona_w1, issue_corona_eco_w1,
                 no_eng_w1), ~ .*wgt_2_w1, na.rm=TRUE) %>% 
    mutate_at(vars(issue_racism_w2, issue_climate_w2,
                 issue_corona_w2, issue_corona_eco_w2,
                 no_eng_w2), ~ .*wgt_2_w1_adj, na.rm=TRUE) %>% 
  mutate_at(vars(contains("issue"), wgt_2_w1, wgt_2_w1_adj, no_eng_w1, no_eng_w2), ~ sum(., na.rm=TRUE)) %>% 
  distinct(.) %>% 
  mutate_at(vars(issue_racism_w1, issue_climate_w1,
                 issue_corona_w1, issue_corona_eco_w1,
                 no_eng_w1), ~ .*100/wgt_2_w1) %>% 
  mutate_at(vars(issue_racism_w2, issue_climate_w2,
                 issue_corona_w2, issue_corona_eco_w2,
                 no_eng_w2), ~ .*100/wgt_2_w1_adj) %>% 
  select(-wgt_2_w1, -wgt_2_w1_adj) %>% 
  pivot_longer(cols=c(contains("issue"), "no_eng_w1", "no_eng_w2"), names_to = "issue", values_to = "value") %>% 
  mutate(type=case_when(grepl("w1", issue) ~ "Ist Wave",
                        grepl("w2", issue) ~ "IInd Wave",
                        TRUE ~ as.character(NA)),
         issue=substr(issue,1,nchar(issue)-3)) %>% 
  pivot_wider(id_cols = "issue", values_from = "value", names_from = "type") %>%   mutate(issue=case_when(issue=="issue_corona" ~ "Corona freedom",
                         issue=="issue_corona_eco" ~ "Corona economic",
                         issue=="issue_corona_other" ~ "Corona and other",
                         issue=="issue_racism" ~ "Against racism",
                         issue=="issue_climate" ~ "Climate prot.",
                         issue=="issue_other" ~ "Other",
                         issue=="no_eng" ~ "No pol. eng.")) %>%
  filter(issue!="No pol. eng.") %>% 
  na.omit()

left_label <- paste0(plot_dat$issue, " (", round(plot_dat$`Ist Wave`), "%)")
right_label <- paste0(plot_dat$issue, " (", round(plot_dat$`IInd Wave`), "%)")
plot_dat$class <- ifelse((plot_dat$`IInd Wave` - plot_dat$`Ist Wave`) < 0, "red", "green")


# Plot
p <- ggplot(plot_dat) + 
  geom_segment(aes(x=1, xend=2, y=`Ist Wave`, yend=`IInd Wave`, col=class), size=.75, show.legend=F) + 
                  geom_vline(xintercept=1, linetype="dashed", size=.1) + 
                  geom_vline(xintercept=2, linetype="dashed", size=.1) +
                  scale_color_manual(labels = c("Up", "Down"), 
                                     values = c("green"="#00ba38", "red"="#f8766d")) +  # color of lines
                  labs(x="", y="Share of engagement (pp.)") +  # Axis labels
                  xlim(-0, 2.9) + ylim(0,(1.1*(max(plot_dat$`Ist Wave`, plot_dat$`IInd Wave`))))  # X and Y axis limits

plot_dat$left_label_y <- plot_dat$`Ist Wave`
plot_dat$right_label_y <- plot_dat$`IInd Wave`


plot_dat <- plot_dat %>% 
  # mutate(left_label_y=ifelse(issue=="Other", left_label_y + 0.3, left_label_y))
  mutate(left_label_y=case_when(issue=="Other" ~ left_label_y - 0.35,
                                issue=="COVID-19 freedom" ~ left_label_y + 0.35,
                                TRUE ~ left_label_y)) %>% 
  mutate(right_label_y=case_when(issue=="Other" ~ right_label_y - 0.35,
                                issue=="COVID-19 freedom" ~ right_label_y + 0.35,
                                issue=="COVID-19 & other" ~ right_label_y - 0.5,
                                issue=="COVID-19 & econ." ~ right_label_y + 0.5,
                                TRUE ~ right_label_y))
  


# Add texts
p <- p + geom_text(label=left_label, y=plot_dat$left_label_y, x=rep(1, NROW(plot_dat)), hjust=1.1, size=3.5)
p <- p + geom_text(label=right_label, y=plot_dat$right_label_y, x=rep(2, NROW(plot_dat)), hjust=-0.1, size=3.5)
p <- p + geom_text(label="Wave 1", x=1, y=1.1*(max(plot_dat$`Ist Wave`, plot_dat$`IInd Wave`)), hjust=1.2, size=5)  # title
p <- p + geom_text(label="Wave 2", x=2, y=1.1*(max(plot_dat$`Ist Wave`, plot_dat$`IInd Wave`)), hjust=-0.1, size=5)  # title
p <- p + geom_text(label="October 14. 2020 -\nNovember 04. 2020\nn=3330   ", x=1, y=0.5, hjust=1.2, size=3)
p <- p + geom_text(label="March 02. 2021 -\nMarch 11. 2021\n n=967", x=2, y=0.5, hjust=-0.1, size=3)

# 02 - 11. 03. 2021
# 14. 10. - 04. 11. 2020


# Minify theme
p + theme(panel.background = element_blank(), 
           panel.grid = element_blank(),
           axis.ticks = element_blank(),
           axis.text.x = element_blank(),
           panel.border = element_blank(),
           plot.margin = unit(c(0.2,-1,0.2,0.2), "cm"))


ggsave(plot=last_plot(),
       filename = "panel_issue_shares.png",
       path = fig_path,
       scale = 1.6,
       # pointsize=6,
       width = 11.1, height = 7.7, dpi=400,
       units="cm") 

```

### Figure 4 Appendix A 

```{r, include = T, echo = F, message = F}

plot_dat <- read_dta(paste0(path, "/data/DE_Panel_complete_wide.dta")) %>%
  select(att_diversity_w1, worr_climate_w1, msr_health_w1, msr_eco_w1, 
         att_diversity_w2, worr_climate_w2, msr_health_w2, msr_eco_w2, 
         wgt_2_w1_adj, wgt_2_w1) %>% 
  pivot_longer(cols=c(att_diversity_w1, worr_climate_w1, msr_health_w1, msr_eco_w1, 
         att_diversity_w2, worr_climate_w2, msr_health_w2, msr_eco_w2), names_to = "type", values_to = "value") %>% 
  mutate(wave=case_when(grepl("w1", type) ~ "Wave 1",
                        grepl("w2", type) ~ "Wave 2",
                        TRUE ~ as.character(NA)),
         type=substr(type,1,nchar(type)-3)) %>% 
  mutate(wgt_2_w1_adj=case_when(wave=="Wave 2" ~ wgt_2_w1_adj,
                                TRUE ~ wgt_2_w1)) %>% 
  select(-wgt_2_w1) %>% 
  filter(!is.na(value)) %>% 
  filter(!is.na(wgt_2_w1_adj)) %>% 
  mutate(labels=case_when(value==1 & type %in% 
                            c("msr_eco", "msr_health") ~ "not at all sufficient", 
                          value==2 & type %in% 
                            c("msr_eco", "msr_health") ~ "rather not sufficient", 
                          value==3 & type %in% 
                            c("msr_eco", "msr_health") ~ "appropriate", 
                          value==4 & type %in% 
                            c("msr_eco", "msr_health") ~ "rather too strong", 
                          value==5 & type %in% 
                            c("msr_eco", "msr_health") ~ "too extreme",
                          value==1 & type == "att_diversity" ~ "completely disagree", 
                          value==2 & type == "att_diversity" ~ "disagree", 
                          value==3 & type == "att_diversity" ~ "either/or", 
                          value==4 & type == "att_diversity" ~ "agree", 
                          value==5 & type == "att_diversity" ~ "completely agree",
                          value==1 & type == "worr_climate" ~ "very concerned", 
                          value==2 & type == "worr_climate" ~ "somewhat concerned", 
                          value==3 & type == "worr_climate" ~ "not concerned")) %>% 
  mutate(labels=factor(labels, levels = c("not at all sufficient", "rather not sufficient", 
                          "appropriate", "rather too strong", 
                          "too extreme", "completely disagree", "disagree", "either/or",
                          "agree", "completely agree", "not concerned", 
                          "somewhat concerned", "very concerned"))) %>% 
  mutate(type=case_when(type=="msr_eco" ~ "Economic measures", 
                        type=="msr_health" ~ "Health measures",
                        type=="att_diversity" ~ "Diversity",
                        type=="worr_climate" ~ "Climate concerns")) %>%
  mutate(type=factor(type, levels=c("Climate concerns", "Diversity",
                                    "Economic measures",
                                    "Health measures"))) %>% 
  mutate(type=fct_rev(type)) %>% 
  mutate(labels_wrap = str_wrap(labels, width = 10)) 

ggplot(plot_dat, aes(x=reorder(labels_wrap, value), color=wave, fill=wave,
                     group=wave, weight=wgt_2_w1_adj)) +
  geom_density(adjust = 2.5, alpha = .3) +
  facet_wrap(~type, scales = "free_x") +
  ylab("Share") +
  theme_linedraw() +
  theme(legend.title=element_blank(), 
        legend.position="bottom",
        axis.title.x=element_blank())
        
ggsave(plot=last_plot(),
       filename = "measures.png",
       path = app_fig_path,
       scale = 1.2,
       width = 6, height = 4, dpi=400)  

```

## Long

```{r, include = T, echo = T, message = F}

pol_controls <- c("lrscale", "msr_health", "msr_eco", "att_diversity", "worr_climate",
                  "polinterest", "trust_state")


forms <- c("pol_demo", "pol_demo_online", "pol_post_online",
         "pol_petition", "pol_cntct_polit")

reg_dat <- read_dta(paste0(path, "data/DE_Panel_complete_long.dta")) %>% 
  mutate(msr_eco=max(msr_eco, na.rm = TRUE)-msr_eco+1,
         worr_climate=max(worr_climate, na.rm = TRUE)-worr_climate+1,
         att_diversity=max(att_diversity, na.rm = TRUE)-att_diversity+1) %>% 
  mutate(wgt_2=ifelse(wave==2 & is.na(wgt_2), wgt_2_wave2, wgt_2)) %>% 
  mutate_at(vars(contains("issue_")), ~ 
              ifelse(((pol_cntct_polit > 1 | pol_party > 1) &
              (pol_demo==1 & pol_demo_online==1 & pol_post_online==1 &
                 pol_petition==1 & pol_demo_illegal==1)), 0, .)) %>% 
  select(pol_controls,  wgt_2, issue_corona, 
         issue_corona_eco, issue_climate, issue_racism, issue_other, wave, c_0001) %>% 
  mutate_at(vars(contains("issue_")), ~ replace_na(., 0)) %>% 
  ungroup(.) %>% 
  na.omit

```


```{r, include = T, echo = T, message = F, warning=FALSE}

M1 <- bife(issue_corona ~  msr_health + msr_eco + att_diversity + worr_climate + polinterest + trust_state + lrscale | c_0001, reg_dat, "logit") # + polinterest + trust_state + lrscale

M2 <- bife(issue_corona_eco ~  msr_health + msr_eco + att_diversity + worr_climate + polinterest + trust_state + lrscale | c_0001, reg_dat, "logit")

M3 <- bife(issue_climate ~ msr_health + msr_eco + att_diversity + worr_climate + polinterest + trust_state + lrscale | c_0001, reg_dat, "logit")

M4 <- bife(issue_racism ~  msr_health + msr_eco + att_diversity + worr_climate + polinterest + trust_state + lrscale | c_0001, reg_dat, "logit")

p <- ggcoefstats(x = M1, conf.level = 0.95)
pg <- ggplot_build(p)
mod1_res <- pg$plot$data %>% 
  mutate(type="COVID-19 freedom") %>% 
  rename(`2.5 %`=conf.low,
         `97.5 %`=conf.high) %>% 
  select(term, estimate, type, `2.5 %`, `97.5 %`)
p <- ggcoefstats(x = M1, conf.level = 0.9)
pg <- ggplot_build(p)
mod1_res2 <- pg$plot$data %>% 
  rename(`5 %`=conf.low,
         `95 %`=conf.high) %>% 
  select(term, `5 %`, `95 %`)

mod0_res <- merge(mod1_res, mod1_res2, by="term", all=TRUE)

p <- ggcoefstats(x = M2, conf.level = 0.95)
pg <- ggplot_build(p)
mod1_res <- pg$plot$data %>% 
  mutate(type="COVID-19 econ.") %>% 
  rename(`2.5 %`=conf.low,
         `97.5 %`=conf.high) %>% 
  select(term, estimate, type, `2.5 %`, `97.5 %`)
p <- ggcoefstats(x = M2, conf.level = 0.9)
pg <- ggplot_build(p)
mod1_res2 <- pg$plot$data %>% 
  rename(`5 %`=conf.low,
         `95 %`=conf.high) %>% 
  select(term, `5 %`, `95 %`)

mod2_res <- merge(mod1_res, mod1_res2, by="term", all=TRUE)

p <- ggcoefstats(x = M3, conf.level = 0.95)
pg <- ggplot_build(p)
mod1_res <- pg$plot$data %>% 
  mutate(type="Climate prot.") %>% 
  rename(`2.5 %`=conf.low,
         `97.5 %`=conf.high) %>% 
  select(term, estimate, type, `2.5 %`, `97.5 %`)
p <- ggcoefstats(x = M3, conf.level = 0.9)
pg <- ggplot_build(p)
mod1_res2 <- pg$plot$data %>% 
  rename(`5 %`=conf.low,
         `95 %`=conf.high) %>% 
  select(term, `5 %`, `95 %`)

mod3_res <- merge(mod1_res, mod1_res2, by="term", all=TRUE)

p <- ggcoefstats(x = M4, conf.level = 0.95)
pg <- ggplot_build(p)
mod1_res <- pg$plot$data %>% 
  mutate(type="Against racism") %>% 
  rename(`2.5 %`=conf.low,
         `97.5 %`=conf.high) %>% 
  select(term, estimate, type, `2.5 %`, `97.5 %`)
p <- ggcoefstats(x = M4, conf.level = 0.9)
pg <- ggplot_build(p)
mod1_res2 <- pg$plot$data %>% 
  rename(`5 %`=conf.low,
         `95 %`=conf.high) %>% 
  select(term, `5 %`, `95 %`)

mod4_res <- merge(mod1_res, mod1_res2, by="term", all=TRUE)


models <- bind_rows(mod0_res, mod2_res, mod3_res, mod4_res)

rm(mod1_res, mod2_res, mod3_res, mod4_res, mod0_res,
   p, pg)

```

## Table 3 Appendix A

```{r, include = T, echo = T, message = F, warning=FALSE, fig.width=6.5, fig.height=10}

### Regression table

Individuals <- c(M3$nobs[4]/2, M4$nobs[4]/2,
         M2$nobs[4]/2, M1$nobs[4]/2)

texreg(l=list(M3, M4, M2, M1), doctype = FALSE, center = TRUE, siunitx=TRUE, use.packages=FALSE, booktabs = TRUE,
       caption = "Fixed effects model of issue specific participation",
       single.row=TRUE, no.margin = TRUE,
       custom.model.names = c("Protection", "Racism",
                              "Economy", "Freedom"),
       custom.header = list("Climate" = 1, "Against" = 2,
                            "COVID-19" = 3, "COVID-19" = 4),
       custom.gof.rows = list("Num. pers." =  Individuals),
       reorder.gof = c(2, 3, 4, 1),
       custom.coef.map = list("worr_climate" = "Climate worries",
                              "att_diversity" = "Diversity",
                              "msr_health" = "Health measures", 
                              "msr_eco" = "Econ. measures",
                              "polinterest" = "Pol. interest",
                              "lrscale" = "L-R position",
                              "trust_state" = "Trust in state"),
       groups = list("Issue positions"=1:4,
                     "Attitudes (controls)" = 5:7),
       file=paste0(tables_path, "/FE_model.tex"))

tex <- readLines(paste0(tables_path, "/FE_model.tex"))
tex <- tex[-8]

writeLines(tex, paste0(tables_path, "/FE_model.tex"))
                                      
```

## Figure 6 Main Text

```{r, include = T, echo = T, message = F, warning=FALSE, fig.width=6.5, fig.height=10}

plot_dat <- models %>% 
  filter(term!="(Intercept)") %>% 
  filter(!(term %in% c("lrscale", "trust_state", "polinterest"))) %>% 
  mutate(odds = exp(estimate),
         odds.outter.upper = exp(`2.5 %`),
         odds.outter.lower = exp(`97.5 %`),
         odds.inner.upper = exp(`5 %`),
         odds.inner.lower = exp(`95 %`),
         probability = odds/(1+odds),
         prob.outter.upper = odds.outter.upper/(1+odds.outter.upper),
         prob.outter.lower = odds.outter.lower/(1+odds.outter.lower),
         prob.inner.upper = odds.inner.upper/(1+odds.inner.upper),
         prob.inner.lower = odds.inner.lower/(1+odds.inner.lower)) %>% 
  mutate(term=str_remove(as.character(term), "as.factor")) %>%
  mutate(term=str_remove(as.character(term), "vote_pref")) %>%
  mutate(term=case_when(term=="msr_eco" ~ "Economic measures",
                        term=="msr_health" ~ "Health measures",
                        term=="att_diversity" ~ "Diversity",
                        term=="worr_climate" ~ "Climate worries",
                        TRUE ~ term))

plot_dat <- plot_dat %>% 
  mutate(term=factor(term, levels = c("Health measures",
                                      "Economic measures", 
                                      "Climate worries",
                                      "Diversity"))) %>%
  # mutate(term=fct_rev(term)) %>% 
  mutate(type=factor(type, levels = c("Climate prot.", "Against racism", 
                                      "COVID-19 econ.", "COVID-19 freedom"))) %>% 
  mutate(type=fct_rev(type)) %>% 
  mutate(new_labels = as.character(term))

space_between_bars <- 0.6

ggplot(plot_dat, aes(y=term, color=type)) +
  geom_vline(xintercept = 1, linetype="dashed", color="gray60") +
  geom_point(aes(x=odds, shape=type), position=position_dodge(width=space_between_bars), size=2) +
  geom_linerange(aes(xmin=odds.outter.lower, xmax=odds.outter.upper, 
                     group=type), size=0.5, position=position_dodge(width=space_between_bars), key_glyph = "path") +
  geom_linerange(aes(xmin=odds.inner.lower, xmax=odds.inner.upper, 
                     group=type), size=1.1, position=position_dodge(width=space_between_bars), key_glyph = "path") +
  xlab("Odds Ratio") +
  # facet_wrap(~facets, scales="free", nrow = 1) +
  scale_color_manual(name="", values=c("#E78AC3", "#8DA0CB", "#FC8D62", "#66C2A5"), guide=guide_legend(reverse = TRUE, nrow=2, byrow=TRUE)) +
  scale_shape_discrete(name="", guide=guide_legend(reverse = TRUE, nrow=2, byrow=TRUE)) +
  scale_y_discrete(labels = function(y) stringr::str_wrap(y, width = 50)) +
  theme_linedraw() +
  theme(legend.title=element_blank(), 
        legend.position="bottom",
        legend.key.width = unit(1,"cm"),
        axis.title.y = element_blank(),
        axis.text.y = element_text(hjust=0.5))

ggsave(plot=last_plot(),
       filename="FE_odds_with_facets.png",
       path = fig_path,
       scale = 1.4,
       width = 4.5, 
       height = 4,
       dpi=400)

```


```{r, include = T, echo = T, message = F, warning=FALSE, fig.width=6.5, fig.height=10}

```